当前位置: 首页 > 工具软件 > GO daemon > 使用案例 >

Golang操作MongoDB:mongo-driver

蔚桐
2023-12-01

1、获取依赖go get "go.mongodb.org/mongo-driver"

2、连接数据库
前提:确保mongo进程已启动:ps -ef|grep mongo

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var db *mongo.Database			// 数据库
var stuColl *mongo.Collection	// 集合

func init() {
	option := options.Client().ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(context.TODO(), option)
	if err != nil {
		log.Fatal(err)
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	log.Print("connect mongo success")
	db = client.Database("test")
	stuColl = db.Collection("student")
}

这里我在当前包的init方法中完成数据库和集合的初始化,这样每次执行该包的方法都会先执行init()函数,保证了数据库和集合的连接。后面进行操作就直接调用全局变量即可。

3、构建文档对应实体类

import (
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type Student struct {
	Id primitive.ObjectID `bson:"_id,omitempty"`
	Name string
	Age int
}

4、操作数据库

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"log"
)

// InsertOne 添加一条记录
func InsertOne(stu Student) {
	one, err := stuColl.InsertOne(context.TODO(), stu)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("insert one success :",one.InsertedID)
}

// InsertMany 添加多条记录
func InsertMany(stu []interface{}) {
	// InsertMany 所需的第二个参数是interface{}型切片
	many, err := stuColl.InsertMany(context.TODO(), stu)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("insert many success :",many.InsertedIDs)
}

// UpdateOne 更新一个文档 若有多个匹配 只更新第一个
func UpdateOne(filter interface{},condition interface{}) {
	one, err := stuColl.UpdateOne(context.TODO(), filter, condition)
	if err != nil {{
		log.Fatal(err)
	}}
	fmt.Println("update match:",one.MatchedCount,"; modify :",one.ModifiedCount)
}

// UpdateMany 更新多个文档
func UpdateMany(filter interface{},condition interface{}) {
	many, err := stuColl.UpdateMany(context.TODO(), filter, condition)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("update match:",many.MatchedCount,"; modify :",many.ModifiedCount)
}

// QueryAll 查询所有
func QueryAll() {
	res := []Student{}
	find, err := stuColl.Find(context.TODO(), bson.M{})
	if err != nil {
		fmt.Println("no match data")
		return
	}
	// 记得关闭游标
	defer find.Close(context.TODO())
	// 遍历游标获取查询到的文档
	for find.Next(context.TODO()) {
		var cur Student
		// 解码find当前行 存到cur
		err = find.Decode(&cur)
		if err != nil {
			log.Fatal(err)
		}
		res = append(res, cur)
	}
	fmt.Printf("%+v\n",&res)
}

// QueryOne 查找一个文档
func QueryOne(filter interface{}) {
	var res Student
	err := stuColl.FindOne(context.TODO(),filter).Decode(&res)
	if err != nil {
		//log.Fatal(err)	// 查不到会报错
		fmt.Println("no match data")
	} else {
		fmt.Printf("%+v\n",res)
	}
}

// QueryMany 查询多个文档x
func QueryMany(filter interface{}) {
	var res []Student
	// 返回的是一个游标
	find, err := stuColl.Find(context.TODO(),filter)
	if err != nil {
		fmt.Println("no match data")
		return
	}
	// 记得关闭游标
	defer find.Close(context.TODO())
	// 遍历游标获取查询到的文档
	for find.Next(context.TODO()) {
		var cur Student
		// 解码find当前行 存到cur
		err = find.Decode(&cur)
		if err != nil {
			log.Fatal(err)
		}
		res = append(res, cur)
	}
	fmt.Printf("%+v\n",&res)
}

// DeleteOne 删除一个文档
func DeleteOne(filter interface{}) {
	one, err := stuColl.DeleteOne(context.TODO(), filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("delete count :",one.DeletedCount)
}

// DeleteMany 删除多个文档
func DeleteMany(filter interface{}) {
	many, err := stuColl.DeleteMany(context.TODO(), filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("delete count :", many.DeletedCount)
}

5、测试

import (
	"go.mongodb.org/mongo-driver/bson"
	"testing"
)

func TestQueryAll(t *testing.T) {
	QueryAll()
}

func TestQueryOne(t *testing.T) {
	filter := bson.M{"name":"lena"}
	QueryOne(filter)
}

func TestQueryMany(t *testing.T) {
	QueryMany(bson.M{"age": 13})
}

func TestInsertOne(t *testing.T) {
	QueryAll()
	stu := Student{Name: "lena",Age: 12}
	InsertOne(stu)
	QueryAll()
}

func TestInsertMany(t *testing.T) {
	stu := []interface{}{
		Student{Name: "test1",Age: 12},
		Student{Name: "test1",Age: 12},
		Student{Name: "test1",Age: 12},
		Student{Name: "test2",Age: 12},
	}
	InsertMany(stu)
}

func TestDeleteOne(t *testing.T) {
	filter := bson.M{"name": "test2"}
	QueryOne(filter)
	DeleteOne(filter)
	QueryOne(filter)
}

func TestDeleteMany(t *testing.T) {
	filter := bson.M{"name": "test1"}
	QueryOne(filter)
	DeleteMany(filter)
	QueryOne(filter)
}

func TestUpdateOne(t *testing.T) {
	condition := bson.M{
		"$set":bson.M{
			"age":18,
		},
	}
	filter := bson.M{"name": "lena"}
	QueryMany(filter)
	UpdateOne(filter,condition)
	QueryMany(filter)
}

func TestUpdateMany(t *testing.T) {
	// 符合条件的age自增1
	condition := bson.M{
		"$inc":bson.M{
			"age":1,
		},
	}
	filter := bson.M{"age": 12}
	QueryMany(filter)
	UpdateMany(filter,condition)
	QueryMany(bson.M{"age":13})
}

官方API:https://pkg.go.dev/go.mongodb.org/mongo-driver#section-readme
参考文章:https://www.liwenzhou.com/posts/Go/go_mongodb/

 类似资料: