Go實(shí)現(xiàn)mongodb增刪改查工具類的代碼示例
1、驅(qū)動(dòng)下載
mongodb官方go介紹
使用例子https://www.mongodb.com/docs/drivers/go/current/fundamentals/connection/#connection-example
快速入門https://www.mongodb.com/docs/drivers/go/current/quick-start/
要對(duì)mongodb進(jìn)行增刪改查,需要添加對(duì)應(yīng)的go驅(qū)動(dòng)依賴,安裝命令
go get go.mongodb.org/mongo-driver/mongo
2、實(shí)現(xiàn)代碼
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 等于,可以省略這個(gè)符號(hào) bson.M{"age": bson.M{"$eq": 20}},bson.M{"age": 20} $in 在范圍內(nèi) bson.M{"age": bson.M{"$in": []int{16, 33}}} $nin 不在范圍內(nèi) bson.M{"age": bson.M{"$nin": []int{16, 33}}} // $inc 對(duì)給定數(shù)值字段數(shù)加減 bson.M{"$inc": bson.M{"age": -5}} $set 設(shè)置字段值,如果字段不存在則創(chuàng)建 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 運(yùn)行效果
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!
總結(jié)
到此這篇關(guān)于Go實(shí)現(xiàn)mongodb增刪改查工具類的文章就介紹到這了,更多相關(guān)Go mongodb增刪改查工具類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言實(shí)戰(zhàn)學(xué)習(xí)之流程控制詳解
這篇文章主要為大家詳細(xì)介紹了Go語言中的流程控制,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Go語言有一定的幫助?,需要的朋友可以參考下2022-08-08Golang使用sqlite3數(shù)據(jù)庫實(shí)現(xiàn)CURD操作
這篇文章主要為大家詳細(xì)介紹了Golang使用sqlite3數(shù)據(jù)庫實(shí)現(xiàn)CURD操作的相關(guān)知識(shí),文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以參考一下2025-03-03Golang學(xué)習(xí)筆記(四):array、slice、map
這篇文章主要介紹了Golang學(xué)習(xí)筆記(四):array、slice、map,本文分別講解了這3個(gè)類型的聲明&賦值、元素訪問、其它操作,需要的朋友可以參考下2015-05-05Golang 實(shí)現(xiàn)Thrift客戶端連接池方式
這篇文章主要介紹了Golang 實(shí)現(xiàn)Thrift客戶端連接池方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Go語言標(biāo)準(zhǔn)庫flag的具體實(shí)現(xiàn)
Go語言的flag庫提供了一套簡(jiǎn)單而強(qiáng)大的接口,用于解析命令行參數(shù),本文主要介紹了Go語言標(biāo)準(zhǔn)庫flag的具體實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03golang對(duì)自定義類型進(jìn)行排序的解決方法
學(xué)習(xí)一門編程語言,要掌握原子數(shù)據(jù)類型,還需要掌握自定義數(shù)據(jù)類型。下面這篇文章主要給大家介紹了關(guān)于golang如何對(duì)自定義類型進(jìn)行排序的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-12-12