go操作mongodb

go操作mongodb

安装mongodb go的驱动

# 使用官方的驱动包
mkdir go_mongo
cd go_mongo
go mod init go_mongo
go get go.mongodb.org/mongo-driver/mongo

使用

1、创建客户端连接mongo数据库

前提是本机安装有mongoDB数据库

ctx, _ := context.WithTimeout(context.Background(),10*time.Second)
	client, err := mongo.Connect(ctx,options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil{
		panic(nil)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil{
		panic(err)
	}
	fmt.Println("connect success")

2、选择数据库和集合

collection := client.Database("mydb").Collection("student")

3、删除这个集合

 collection.Drop(ctx)

4、插入一条文档数据

func insertOneDoc(collection *mongo.Collection, ctx context.Context,obj interface{}){
	// insert doc
	insertResult, err := collection.InsertOne(ctx, obj)
	if err != nil{
		panic(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

5、插入多条文档数据

func insertManyDoc(collection *mongo.Collection, ctx context.Context,obj []interface{})  {
	//students := []interface{}{obj} //slice
	insertManyResult,err := collection.InsertMany(ctx,obj)
	if err != nil{
		panic(err)
	}
	fmt.Println("inserted multiple document:",insertManyResult.InsertedIDs)
}

6、更新文档

func updateDoc(collection *mongo.Collection, ctx context.Context,filter interface{},update interface{}){
	updateResult, err :=collection.UpdateMany(ctx,filter,update)
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

}
// 调用
filter := bson.D{{"name","mike"}}
	update :=bson.D{
		{"$inc", bson.D{
			{"age",1}, // 增加1岁
		}},
	}
	updateResult, err :=collection.UpdateOne(ctx,filter,update)
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

7、查找文档

查找多个

// 将选项传递给Find()
	findOptions := options.Find()
	findOptions.SetLimit(2)

	// 定义一个切片用来存储查询结果
	var results []*Student

	// 把bson.D{{}}作为一个filter来匹配所有文档
	cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 查找多个文档返回一个光标
	// 遍历游标允许我们一次解码一个文档
	for cur.Next(context.TODO()) {
		// 创建一个值,将单个文档解码为该值
		var elem Student
		err := cur.Decode(&elem)
		if err != nil {
			log.Fatal(err)
		}
		results = append(results, &elem)
	}
	//
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

	// 完成后关闭游标
	cur.Close(context.TODO())
	fmt.Printf("Found multiple documents (array of pointers): %#v\n", results)

查找单条

var result Student
	filter = bson.D{{"name", "小黄"}}
	err = collection.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found a single document: %+v\n", result)

8、删除文档

删除一条

deleteResult ,err := collection.DeleteOne(ctx,bson.D{{"name","mike"}})
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

删除多条

deleteResult1, err := collection.DeleteMany(ctx,bson.D{{"age",10}})
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
	fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult1.DeletedCount)
}

完整练习代码:

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
	"time"
)
type Student struct{
	Name string `json:"name"`
	Age int		`json:"age"`
}
func insertOneDoc(collection *mongo.Collection, ctx context.Context,obj interface{}){
	// insert doc
	insertResult, err := collection.InsertOne(ctx, obj)
	if err != nil{
		panic(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}
func insertManyDoc(collection *mongo.Collection, ctx context.Context,obj []interface{})  {
	//students := []interface{}{obj} //slice
	insertManyResult,err := collection.InsertMany(ctx,obj)
	if err != nil{
		panic(err)
	}
	fmt.Println("inserted multiple document:",insertManyResult.InsertedIDs)
}

func updateDoc(collection *mongo.Collection, ctx context.Context,filter interface{},update interface{}){
	//update :=bson.D{
	//	{"$inc", bson.D{
	//		{"age",1},
	//	}},
	//}
	updateResult, err :=collection.UpdateMany(ctx,filter,update)
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

}
func main() {
	//clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	//
	//client, err := mongo.Connect(context.TODO(), clientOptions)
	//if err != nil{
	//	panic(err)
	//}
	//// 检查连接
	//err = client.Ping(context.TODO(),nil)
	//if err !=nil{
	//	panic(err)
	//}
	//fmt.Println("连接成功")

	// 官方推荐的连接方式
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s超时
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(nil)
	}
	// 检测连接
	err = client.Ping(ctx, readpref.Primary()) // primary表示主节点
	if err != nil {
		panic(err)
	}
	fmt.Println("connect success")

	// 连接数据库
	collection := client.Database("mydb").Collection("student")
	collection.Drop(ctx)
	// 返回游标
	//cur,err := collection.Find(ctx,bson.D{})
	//if err !=nil{
	//	panic(err)
	//}
	//defer cur.Close(ctx)
	//for cur.Next(ctx){
	//	var result bson.M
	//	err := cur.Decode(&result)
	//	if err !=nil{
	//		log.Fatal(err)
	//	}
	//}
	//if err := cur.Err(); err !=nil{
	//	log.Fatal(err)
	//}

	// 返回结果
	//var student Student
	//filter := bson.D{{"name", "mike"}}
	//err = collection.FindOne(ctx, filter).Decode(&student)
	//if err != nil {
	//	//panic(err)
	//	log.Fatal(err)
	//
	//}
	//fmt.Printf("Found a single document: %+v\n", student)

	// 插入文档
	//s1 := Student{"小红虹", 12}
	//s2 := Student{"小兰蓝", 10}
	//s3 := Student{"小黄黄", 11}
	//insertOneDoc(collection,ctx,s1)
	//students := []interface{}{s2,s3} //slice
	//insertManyDoc(collection,ctx,students)

	// 更新文档
	filter := bson.D{{"name","mike"}}
	update :=bson.D{
		{"$inc", bson.D{
			{"age",1}, // 增加1岁
		}},
	}
	updateResult, err :=collection.UpdateOne(ctx,filter,update)
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
	//updateDoc(collection,ctx,filter,update)

	// 查找文档
	var result Student
	filter = bson.D{{"name", "小黄"}}
	err = collection.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found a single document: %+v\n", result)
	// 查找多个
	// 查询多个
	// 将选项传递给Find()
	findOptions := options.Find()
	findOptions.SetLimit(2)

	// 定义一个切片用来存储查询结果
	var results []*Student

	// 把bson.D{{}}作为一个filter来匹配所有文档
	cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 查找多个文档返回一个光标
	// 遍历游标允许我们一次解码一个文档
	for cur.Next(context.TODO()) {
		// 创建一个值,将单个文档解码为该值
		var elem Student
		err := cur.Decode(&elem)
		if err != nil {
			log.Fatal(err)
		}
		results = append(results, &elem)
	}
	//
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

	// 完成后关闭游标
	cur.Close(context.TODO())
	fmt.Printf("Found multiple documents (array of pointers): %#v\n", results)


	// 删除文档
	deleteResult ,err := collection.DeleteOne(ctx,bson.D{{"name","mike"}})
	if err !=nil{
		log.Fatal(err)
	}
	fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

	// 删除多个
	deleteResult1, err := collection.DeleteMany(ctx,bson.D{{"age",10}})
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
	fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult1.DeletedCount)
}

参考学习博客:

https://www.liwenzhou.com/posts/Go/go_mongodb/#autoid-0-3-5

https://www.jianshu.com/p/0344a21e8040
官方文档:
https://godoc.org/go.mongodb.org/mongo-driver/mongo

你可能感兴趣的:(go,mongo)