• golang访问MongoDB数据库


    最常用的第三方驱动

    package main
    
    import (
    	"fmt"
    	_ "github.com/sbunce/bson"
    	"gopkg.in/mgo.v2"
    	"labix.org/v2/mgo/bson"
    )
    
    //type Student struct {
    //Name   string `bson: "name"`
    //Age    int    `bson: "age"`
    //Sid    string `bson: "sid"`
    //Status int    `bson: "status"`
    //}
    
    type Student struct {
    	Name   string
    	Age    int
    	Sid    string
    	Status int
    }
    type Per struct {
    	Per []Student
    }
    
    var (
    	ip = "172.17.0.3"
    )
    
    func main() {
    	fmt.Println("vim-go")
    	b := insert()
    	fmt.Printf("插入数据,%v
    ", b)
    
    	b = findOne()
    	b = findAll()
    }
    
    func insert() bool {
    	mongo, err := mgo.Dial(ip) // 建立连接
    
    	defer mongo.Close()
    
    	if err != nil {
    		return false
    	}
    
    	client := mongo.DB("mydb_tutorial").C("t_student") //选择数据库和集合
    
    	//创建数据
    	data := Student{
    		Name:   "学习MongoDB的第一课",
    		Age:    18,
    		Sid:    "learn_001",
    		Status: 1,
    	}
    
    	//插入数据
    	cErr := client.Insert(&data)
    
    	if cErr != nil {
    		return false
    	}
    	return true
    }
    
    func findOne() bool {
    	mongo, err := mgo.Dial(ip)
    
    	defer mongo.Close()
    
    	if err != nil {
    		return false
    	}
    
    	client := mongo.DB("mydb_tutorial").C("t_student")
    
    	user := Student{}
    	//查找sid为 s20180907
    	cErr := client.Find(bson.M{"sid": "learn_001"}).One(&user)
    
    	if cErr != nil {
    		return false
    	}
    
    	fmt.Println(user)
    
    	return true
    
    }
    
    func findAll() bool {
    	mongo, err := mgo.Dial(ip)
    
    	defer mongo.Close()
    
    	if err != nil {
    		return false
    	}
    
    	client := mongo.DB("mydb_tutorial").C("t_student")
    
    	//每次最多输出15条数据
    	iter := client.Find(bson.M{"status": 1}).Sort("_id").Skip(1).Limit(15).Iter()
    
    	var stu Student
    	var users Per
    	for iter.Next(&stu) {
    		users.Per = append(users.Per, stu)
    	}
    
    	if err := iter.Close(); err != nil {
    		return false
    	}
    	fmt.Println(users)
    	return true
    }
    
    //func update() bool {
    //mongo, err := mgo.Dial("192.168.0.91")
    
    //defer mongo.Close()
    
    //if err != nil {
    //return false
    //}
    
    //client := mongo.DB("mydb_tutorial").C("t_student")
    
    ////只更新一条
    //cErr := client.Update(bson.M{"status": 1}, bson.M{"$set": bson.M{"age": 20}})
    
    //if cErr != nil {
    
    //return false
    //}
    
    //return true
    //}
    
    //func del() bool {
    //mongo, err := mgo.Dial("192.168.0.91")
    
    //defer mongo.Close()
    
    //if err != nil {
    //return false
    //}
    
    //client := mongo.DB("mydb_tutorial").C("t_student")
    
    ////只更新一条
    //cErr := client.Remove(bson.M{"sid": "s20180907"})
    
    //if cErr != nil {
    
    //return false
    //}
    
    //return true
    
    //}
    

    MongoDB官方驱动

    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    
    	"go.mongodb.org/mongo-driver/bson"
    	"go.mongodb.org/mongo-driver/mongo"
    	"go.mongodb.org/mongo-driver/mongo/options"
    )
    
    // You will be using this Trainer type later in the program
    type Trainer struct {
    	Name string
    	Age  int
    	City string
    }
    
    func main() {
    	// Rest of the code will go here
    	// Set client options 设置连接参数
    	clientOptions := options.Client().ApplyURI("mongodb://172.17.0.3:27017")
    
    	// Connect to MongoDB 连接数据库
    	client, err := mongo.Connect(context.TODO(), clientOptions)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Check the connection 测试连接
    	err = client.Ping(context.TODO(), nil)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Println("Connected to MongoDB!")
    
    	collection := client.Database("test").Collection("trainers")
    
    	ash := Trainer{"Ash", 10, "Pallet Town"}
    	misty := Trainer{"Misty", 10, "Cerulean City"}
    	brock := Trainer{"Brock", 15, "Pewter City"}
    
    	insertResult, err := collection.InsertOne(context.TODO(), ash)
    	if err != nil {
    		log.Fatal(err)
    	}
    	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
    
    	// 插入多个文档数据
    	trainers := []interface{}{misty, brock}
    
    	insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
    
    	// 更新文档
    	filter := bson.D{{"name", "Ash"}}
    
    	// 年龄加1,$inc 可能是运算符
    	update := bson.D{
    		{"$inc", bson.D{
    			{"age", 1},
    		}},
    	}
    
    	updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Printf("Matched %v documents and updated %v documents.
    ", updateResult.MatchedCount, updateResult.ModifiedCount)
    
    	// 查找Find
    	// create a value into which the result can be decoded
    	var result Trainer
    
    	err = collection.FindOne(context.TODO(), filter).Decode(&result)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Printf("Found a single document: %+v
    ", result)
    
    	// 查找多个文档
    	// Pass these options to the Find method,指定查询记录的条数
    	findOptions := options.Find()
    	findOptions.SetLimit(2)
    
    	// Here's an array in which you can store the decoded documents
    	var results []*Trainer
    
    	// Passing bson.D{{}} as the filter matches all documents in the collection
    	// bson.D{{}} 相当没有条件
    	cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Finding multiple documents returns a cursor
    	// Iterating through the cursor allows us to decode documents one at a time
    	// 通过游标遍历记录
    	for cur.Next(context.TODO()) {
    
    		// create a value into which the single document can be decoded
    		var elem Trainer
    		err := cur.Decode(&elem)
    		if err != nil {
    			log.Fatal(err)
    		}
    
    		results = append(results, &elem)
    	}
    
    	if err := cur.Err(); err != nil {
    		log.Fatal(err)
    	}
    
    	// Close the cursor once finished
    	cur.Close(context.TODO())
    
    	fmt.Printf("Found multiple documents (array of pointers): %+v
    ", results)
    
    	// 删除所有的记录
    	deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
    	if err != nil {
    		log.Fatal(err)
    	}
    	fmt.Printf("Deleted %v documents in the trainers collection
    ", deleteResult.DeletedCount)
    
    	// 断开连接
    	err = client.Disconnect(context.TODO())
    
    	if err != nil {
    		log.Fatal(err)
    	}
    	fmt.Println("Connection to MongoDB closed.")
    
    }
    
  • 相关阅读:
    链表操作
    建立简单的链表
    scanf()函数用法小结
    快速求某年某月是第几天(未整理)
    合并两个有序数组(未整理)
    如何配置JAVA的环境变量、Tomcat环境变量
    【动态规划】流水作业调度问题与Johnson法则
    分治法(二)
    分治法(一)
    HTML5入门十一---Canvas画布实现画图(二)
  • 原文地址:https://www.cnblogs.com/jiftle/p/12292033.html
Copyright © 2020-2023  润新知