Go实现mongodb增删改查的工具类

1、驱动下载

mongodb官方go介绍
使用例子https://www.mongodb.com/docs/drivers/go/current/fundamentals/connection/#connection-example
快速入门https://www.mongodb.com/docs/drivers/go/current/quick-start/

要对mongodb进行增删改查,需要添加对应的go驱动依赖,安装命令

go get go.mongodb.org/mongo-driver/mongo

2、实现代码

2.1 Mongodb工具类代码

封装的工具类mongodao.go

package dao

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

type MondoDao struct {
	client     *mongo.Client
	db         *mongo.Database
	collection *mongo.Collection
}

func (dao *MondoDao) Connect(url string, db string, collection string) {
	var err error
	dao.client, err = mongo.Connect(context.TODO(), options.Client().SetConnectTimeout(time.Second*10).ApplyURI(url))
	if err != nil {
		log.Fatal(err)
	}
	dao.db = dao.client.Database(db)
	dao.collection = dao.db.Collection(collection)
}

// 插入一行
func (dao *MondoDao) InsertOne(obj any) (interface{}, error) {
	result, err := dao.collection.InsertOne(context.TODO(), obj)
	if err == nil {
		return result.InsertedID, err
	}
	return nil, err
}

// 插入多行
func (dao *MondoDao) InsertMany(objs []any) ([]interface{}, error) {
	result, err := dao.collection.InsertMany(context.TODO(), objs)
	if err != nil {
		return nil, err
	}
	return result.InsertedIDs, nil
}

// 查询一行
func (dao *MondoDao) FindOne(filter bson.M, obj any) error {
	result := dao.collection.FindOne(context.TODO(), filter)
	if result.Err() == nil {
		err := result.Decode(obj)
		return err
	}
	return result.Err()
}

// 查询多行
func (dao *MondoDao) FindMany(filter bson.M, obj any) error {
	cursor, err := dao.collection.Find(context.TODO(), filter)
	defer cursor.Close(context.TODO())
	if err == nil {
		err = cursor.All(context.TODO(), obj)
	}
	return err
}

// 分布查询多行
func (dao *MondoDao) FindManyByPage(filter bson.M, obj any, page int64, pagesize int64, sort bson.M) error {
	options := options.Find().SetSkip((page - 1) * pagesize).SetLimit(pagesize).SetSort(sort)
	cursor, err := dao.collection.Find(context.TODO(), filter, options)
	defer cursor.Close(context.TODO())
	if err == nil {
		err = cursor.All(context.TODO(), obj)
	}
	return err
}

// 删除一行
func (dao *MondoDao) DeleteOne(filter bson.M) (int64, error) {
	result, err := dao.collection.DeleteOne(context.TODO(), filter)
	if err == nil {
		return result.DeletedCount, err
	}
	return 0, err
}

// 删除多行
func (dao *MondoDao) DeleteMany(filter bson.M) (int64, error) {
	result, err := dao.collection.DeleteMany(context.TODO(), filter)
	if err == nil {
		return result.DeletedCount, err
	}
	return 0, err
}

// 删除集合
func (dao *MondoDao) DropCollection() error {
	err := dao.collection.Drop(context.TODO())
	//if err = nil {
	//	log.Fatal("drop collection %v", err)
	//}
	return err
}

// 更新一行
func (dao *MondoDao) UpdateOne(filter bson.M, update bson.M) (int64, error) {
	result, err := dao.collection.UpdateOne(context.TODO(), filter, update)
	if err == nil {
		return result.ModifiedCount, err
	}
	return 0, err
}

// 更新多行
func (dao *MondoDao) UpdateMany(filter bson.M, update bson.M) (int64, error) {
	result, err := dao.collection.UpdateMany(context.TODO(), filter, update)
	if err == nil {
		return result.ModifiedCount, err
	}
	return 0, err
}

/**
// 条件查询
$lt  	小于 				bson.M{"age": bson.M{"$lt": 20}}
$gt 	 大于 				bson.M{"age": bson.M{"$gt": 20}}
$lte 	小于等于 			bson.M{"age": bson.M{"$lte": 20}} bson.D{{"age", bson.D{{"$lte", 20}}}}
$gte 	大于等于 			bson.M{"age": bson.M{"$gte": 20}}
$ne 	不等于 				bson.M{"age": bson.M{"$ne": 20}}
$eq 	等于,可以省略这个符号 	bson.M{"age": bson.M{"$eq": 20}},bson.M{"age": 20}
$in 	在范围内 			bson.M{"age": bson.M{"$in": []int{16, 33}}}
$nin 	不在范围内 			bson.M{"age": bson.M{"$nin": []int{16, 33}}}
//
$inc 	对给定数值字段数加减 bson.M{"$inc": bson.M{"age": -5}}
$set 	设置字段值,如果字段不存在则创建 bson.M{"$set": bson.M{"age": 100}}
$unset 移除字段 {'$unset':{'Name':""}}
*/

2.2 使用例子

使用例子

package main

import (
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"log"
	"mymongodb/dao"
)

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

func (s User) String() string {
	return fmt.Sprintf("%v %v %v", s.ID.Hex(), s.Name, s.Age)
}
func main() {
	dao := dao.MondoDao{}
	url := "mongodb://127.0.0.1:27017"
	dao.Connect(url, "gotest", "user")

	user1 := User{Name: "user1", Age: 66}
	id, _ := dao.InsertOne(user1)
	fmt.Printf("InsertOne id:%v\n", (id.(primitive.ObjectID)).Hex())

	user2 := []any{
		User{Name: "user2", Age: 66},
		User{Name: "user3_3", Age: 76},
		User{Name: "user3_4", Age: 88},
	}
	ids, _ := dao.InsertMany(user2)
	for index, id := range ids {
		fmt.Printf("InsertMany id:%v=%v\n", index, (id.(primitive.ObjectID)).Hex())
	}

	filter3 := bson.M{"name": "user2", "age": 66}
	var user3 User
	err := dao.FindOne(filter3, &user3)
	fmt.Printf("Findone user3:%v, %v\n", user3, err)

	var user4 []User
	filter4 := bson.M{"age": bson.M{"$gt": 60}}
	err4 := dao.FindMany(filter4, &user4)
	if err4 == nil {
		for index, v := range user4 {
			fmt.Printf("FindMany user4:%v, %v, \n", index, v)
		}
	}

	var users5 []User
	filter5 := bson.M{"age": bson.M{"$gt": 65}}
	sort := bson.M{"age": 1}
	err5 := dao.FindManyByPage(filter5, &users5, 1, 10, sort)
	if err5 == nil {
		for index, v := range users5 {
			fmt.Printf("FindManyByPage user5:%v, %v\n", index, v.String())
		}
	}

	filter8 := bson.M{"name": "user2"}
	update8 := bson.M{"$inc": bson.M{"age": +6}}
	count8, err8 := dao.UpdateOne(filter8, update8)
	fmt.Printf("UpdateOne count:%v, %v\n", count8, err8)

	filter9 := bson.M{"$or": []bson.M{bson.M{"name": "user1"}, bson.M{"name": "user2"}}}
	update9 := bson.M{"$set": bson.M{"age": 90}}
	count9, err9 := dao.UpdateMany(filter9, update9)
	fmt.Printf("UpdateMany count:%v, %v\n", count9, err9)

	filter6 := bson.M{"name": "user1", "age": 90}
	deletecount6, err6 := dao.DeleteOne(filter6)
	fmt.Printf("DeleteOne count:%v, %v\n", deletecount6, err6)

	filter7 := bson.M{"age": bson.M{"$gte": 66}}
	deletecount7, err7 := dao.DeleteMany(filter7)
	fmt.Printf("DeleteMany count:%v, %v\n", deletecount7, err7)

	err10 := dao.DropCollection()
	if err10 == nil {
		fmt.Println("drop Collection success!")
	} else {
		log.Fatal("drop collection error,%v", err)
	}
}

2.3 运行效果

D:\project\go\gotest\sql\mongodb>go run main.go
InsertOne id:64d32053a61a1841b70e129a
InsertMany id:0=64d32054a61a1841b70e129b
InsertMany id:1=64d32054a61a1841b70e129c
InsertMany id:2=64d32054a61a1841b70e129d
Findone user3:64d32054a61a1841b70e129b user2 66, <nil>
FindMany user4:0, 64d32053a61a1841b70e129a user1 66, 
FindMany user4:1, 64d32054a61a1841b70e129b user2 66, 
FindMany user4:2, 64d32054a61a1841b70e129c user3_3 76, 
FindMany user4:3, 64d32054a61a1841b70e129d user3_4 88, 
FindManyByPage user5:0, 64d32053a61a1841b70e129a user1 66
FindManyByPage user5:1, 64d32054a61a1841b70e129b user2 66
FindManyByPage user5:2, 64d32054a61a1841b70e129c user3_3 76
FindManyByPage user5:3, 64d32054a61a1841b70e129d user3_4 88
UpdateOne count:1, <nil>
UpdateMany count:2, <nil>
DeleteOne count:1, <nil>
DeleteMany count:3, <nil>
drop Collection success!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

penngo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值