利用golang驅(qū)動(dòng)操作MongoDB數(shù)據(jù)庫(kù)的步驟
安裝MongoDB驅(qū)動(dòng)程序
mkdr mongodb cd mongodb go mod init go get go.mongodb.org/mongo-driver/mongo
連接MongoDB
創(chuàng)建一個(gè)main.go文件
將以下包導(dǎo)入main.go文件中
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" "time" )
連接MongoDB的URI格式為
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
單機(jī)版
mongodb://localhost:27017
副本集
mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017 /?replicaSet = myRepl
分片集群
mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017
mongo.Connect()接受Context和options.ClientOptions對(duì)象,該對(duì)象用于設(shè)置連接字符串和其他驅(qū)動(dòng)程序設(shè)置。
通過(guò)context.TODO()表示不確定現(xiàn)在使用哪種上下文,但是會(huì)在將來(lái)添加一個(gè)
使用Ping方法來(lái)檢測(cè)是否已正常連接MongoDB
func main() { clientOptions := options.Client().ApplyURI("mongodb://admin:password@localhost:27017") var ctx = context.TODO() // Connect to MongoDB client, err := mongo.Connect(ctx, clientOptions) if err != nil { log.Fatal(err) } // Check the connection err = client.Ping(ctx, nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") defer client.Disconnect(ctx)
列出所有數(shù)據(jù)庫(kù)
databases, err := client.ListDatabaseNames(ctx, bson.M{}) if err != nil { log.Fatal(err) } fmt.Println(databases)
在GO中使用BSON對(duì)象
MongoDB中的JSON文檔以稱為BSON(二進(jìn)制編碼的JSON)的二進(jìn)制表示形式存儲(chǔ)。與其他將JSON數(shù)據(jù)存儲(chǔ)為簡(jiǎn)單字符串和數(shù)字的數(shù)據(jù)庫(kù)不同,BSON編碼擴(kuò)展了JSON表示形式,例如int,long,date,float point和decimal128。這使應(yīng)用程序更容易可靠地處理,排序和比較數(shù)據(jù)。Go Driver有兩種系列用于表示BSON數(shù)據(jù):D系列類型和Raw系列類型。
D系列包括四種類型:
- D:BSON文檔。此類型應(yīng)用在順序很重要的場(chǎng)景下,例如MongoDB命令。
- M:無(wú)序map。除不保留順序外,與D相同。
- A:一個(gè)BSON數(shù)組。
- E:D中的單個(gè)元素。
插入數(shù)據(jù)到MongoDB
插入單條文檔
//定義插入數(shù)據(jù)的結(jié)構(gòu)體 type sunshareboy struct { Name string Age int City string } //連接到test庫(kù)的sunshare集合,集合不存在會(huì)自動(dòng)創(chuàng)建 collection := client.Database("test").Collection("sunshare") wanger:=sunshareboy{"wanger",24,"北京"} insertOne,err :=collection.InsertOne(ctx,wanger) if err != nil { log.Fatal(err) } fmt.Println("Inserted a Single Document: ", insertOne.InsertedID)
執(zhí)行結(jié)果如下

#### 同時(shí)插入多條文檔
```go
collection := client.Database("test").Collection("sunshare")
dongdong:=sunshareboy{"張冬冬",29,"成都"}
huazai:=sunshareboy{"華仔",28,"深圳"}
suxin:=sunshareboy{"素心",24,"甘肅"}
god:=sunshareboy{"劉大仙",24,"杭州"}
qiaoke:=sunshareboy{"喬克",29,"重慶"}
jiang:=sunshareboy{"姜總",24,"上海"}
//插入多條數(shù)據(jù)要用到切片
boys:=[]interface{}{dongdong,huazai,suxin,god,qiaoke,jiang}
insertMany,err:= collection.InsertMany(ctx,boys)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertMany.InsertedIDs)
從MongDB中查詢數(shù)據(jù)
查詢單個(gè)文檔
查詢單個(gè)文檔使用collection.FindOne()函數(shù),需要一個(gè)filter文檔和一個(gè)可以將結(jié)果解碼為其值的指針
var result sunshareboy filter := bson.D{{"name","wanger"}} err = collection.FindOne(context.TODO(), filter).Decode(&result) if err != nil { log.Fatal(err) } fmt.Printf("Found a single document: %+v\n", result)
返回結(jié)果如下
Connected to MongoDB!
Found a single document: {Name:wanger Age:24 City:北京}
Connection to MongoDB closed.
查詢多個(gè)文檔
查詢多個(gè)文檔使用collection.Find()函數(shù),這個(gè)函數(shù)會(huì)返回一個(gè)游標(biāo),可以通過(guò)他來(lái)迭代并解碼文檔,當(dāng)?shù)瓿珊螅P(guān)閉游標(biāo)
- Find函數(shù)執(zhí)行find命令并在集合中的匹配文檔上返回Cursor。
- filter參數(shù)必須是包含查詢運(yùn)算符的文檔,并且可以用于選擇結(jié)果中包括哪些文檔。不能為零。空文檔(例如bson.D {})應(yīng)用于包含所有文檔。
- opts參數(shù)可用于指定操作的選項(xiàng),例如我們可以設(shè)置只返回五條文檔的限制(https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#Find)。
//定義返回文檔數(shù)量 findOptions := options.Find() findOptions.SetLimit(5) //定義一個(gè)切片存儲(chǔ)結(jié)果 var results []*sunshareboy //將bson.D{{}}作為一個(gè)filter來(lái)匹配所有文檔 cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions) if err != nil { log.Fatal(err) } //查找多個(gè)文檔返回一個(gè)游標(biāo) //遍歷游標(biāo)一次解碼一個(gè)游標(biāo) for cur.Next(context.TODO()) { //定義一個(gè)文檔,將單個(gè)文檔解碼為result var result sunshareboy err := cur.Decode(&result) if err != nil { log.Fatal(err) } results = append(results, &result) } fmt.Println(result) if err := cur.Err(); err != nil { log.Fatal(err) } //遍歷結(jié)束后關(guān)閉游標(biāo) cur.Close(context.TODO()) fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
返回結(jié)果如下
Connected to MongoDB!
{wanger 24 北京}
{張冬冬 29 成都}
{華仔 28 深圳}
{素心 24 甘肅}
{劉大仙 24 杭州}
Found multiple documents (array of pointers): &[0xc000266450 0xc000266510 0xc000266570 0xc0002665d0 0xc000266630]
Connection to MongoDB closed.
更新MongoDB文檔
更新單個(gè)文檔
更新單個(gè)文檔使用collection.UpdateOne()函數(shù),需要一個(gè)filter來(lái)匹配數(shù)據(jù)庫(kù)中的文檔,還需要使用一個(gè)update文檔來(lái)更新操作
- filter參數(shù)必須是包含查詢運(yùn)算符的文檔,并且可以用于選擇要更新的文檔。不能為零。如果過(guò)濾器不匹配任何文檔,則操作將成功,并且將返回MatchCount為0的UpdateResult。如果過(guò)濾器匹配多個(gè)文檔,將從匹配的集合中選擇一個(gè),并且MatchedCount等于1。
- update參數(shù)必須是包含更新運(yùn)算符的文檔(https://docs.mongodb.com/manual/reference/operator/update/),并且可以用于指定要對(duì)所選文檔進(jìn)行的修改。它不能為nil或?yàn)榭铡?/li>
- opts參數(shù)可用于指定操作的選項(xiàng)。
filter := bson.D{{"name","張冬冬"}} //如果過(guò)濾的文檔不存在,則插入新的文檔 opts := options.Update().SetUpsert(true) update := bson.D{ {"$set", bson.D{ {"city", "北京"}}, }} result, err := collection.UpdateOne(context.TODO(), filter, update,opts) if err != nil { log.Fatal(err) } if result.MatchedCount != 0 { fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount) } if result.UpsertedCount != 0 { fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID) }
返回結(jié)果如下
Connected to MongoDB!
Matched 1 documents and updated 1 documents.
Connection to MongoDB closed.
更新多個(gè)文檔
更新多個(gè)文檔使用collection.UpdateOne()函數(shù),參數(shù)與collection.UpdateOne()函數(shù)相同
filter := bson.D{{"city","北京"}} //如果過(guò)濾的文檔不存在,則插入新的文檔 opts := options.Update().SetUpsert(true) update := bson.D{ {"$set", bson.D{ {"city", "鐵嶺"}}, }} result, err := collection.UpdateMany(context.TODO(), filter, update,opts) if err != nil { log.Fatal(err) } if result.MatchedCount != 0 { fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount) } if result.UpsertedCount != 0 { fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID) }
返回結(jié)果如下
Connected to MongoDB!
Matched 2 documents and updated 2 documents.
Connection to MongoDB closed.
刪除MongoDB文檔
可以使用collection.DeleteOne()或collection.DeleteMany()刪除文檔。如果你傳遞bson.D{{}}作為過(guò)濾器參數(shù),它將匹配數(shù)據(jù)集中的所有文檔。還可以使用collection. drop()刪除整個(gè)數(shù)據(jù)集。
filter := bson.D{{"city","鐵嶺"}} deleteResult, err := collection.DeleteMany(context.TODO(), filter) if err != nil { log.Fatal(err) } fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)
返回結(jié)果如下
Connected to MongoDB!
Deleted 2 documents in the trainers collection
Connection to MongoDB closed.
獲取MongoDB服務(wù)狀態(tài)
上面我們介紹了對(duì)MongoDB的CRUD,其實(shí)還支持很多對(duì)mongoDB的操作,例如聚合、事物等,接下來(lái)介紹一下使用golang獲取MongoDB服務(wù)狀態(tài),執(zhí)行后會(huì)返回一個(gè)bson.Raw類型的數(shù)據(jù)
ctx, _ = context.WithTimeout(context.Background(), 30*time.Second) serverStatus, err := client.Database("admin").RunCommand( ctx, bsonx.Doc{{"serverStatus", bsonx.Int32(1)}}, ).DecodeBytes() if err != nil { fmt.Println(err) } fmt.Println(serverStatus) fmt.Println(reflect.TypeOf(serverStatus)) version, err := serverStatus.LookupErr("version") fmt.Println(version.StringValue()) if err != nil { fmt.Println(err) }
參考鏈接
- https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial
- https://godoc.org/go.mongodb.org/mongo-driver/mongo
到此這篇關(guān)于利用golang驅(qū)動(dòng)操作MongoDB數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)golang驅(qū)動(dòng)操作MongoDB內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mongodb文檔和數(shù)組的通配符索引應(yīng)用小結(jié)
Mongodb的通配符索引,為靈活可變的Mongodb數(shù)據(jù)結(jié)構(gòu)提供了高效的查詢方法,本文結(jié)合Mongodb官方文檔,詳細(xì)介紹在嵌入式文檔和數(shù)組上,通配符索引的結(jié)構(gòu),感興趣的朋友一起看看吧2024-07-07mongodb運(yùn)維_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了mongodb運(yùn)維的相關(guān)知識(shí),非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧2017-08-08MongoDB 索引創(chuàng)建和查詢優(yōu)化的方法
這篇文章主要介紹了MongoDB 索引創(chuàng)建和查詢優(yōu)化的方法,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07cgroup限制mongodb進(jìn)程內(nèi)存大小
這篇文章主要介紹了cgroup限制mongodb進(jìn)程內(nèi)存大小,需要的朋友可以參考下2014-07-07MongoDB中aggregate()方法實(shí)例詳解
MongoDB中聚合(aggregate)主要用于處理數(shù)據(jù)(諸如統(tǒng)計(jì)平均值,求和等),并返回計(jì)算后的數(shù)據(jù)結(jié)果,下面這篇文章主要給大家介紹了關(guān)于MongoDB中aggregate()方法的相關(guān)資料,需要的朋友可以參考下2023-01-01MongoDB的復(fù)合通配符索引及應(yīng)用場(chǎng)景
MongoDB的復(fù)合通配符索引為處理復(fù)雜和多變的數(shù)據(jù)結(jié)構(gòu)提供了靈活的索引解決方案,通過(guò)合理使用復(fù)合通配符索引,可以顯著提高查詢效率并減少索引維護(hù)成本,本文給大家介紹MongoDB的復(fù)合通配符索引,感興趣的朋友跟隨小編一起看看吧2024-08-08MongoDB排序時(shí)內(nèi)存大小限制與創(chuàng)建索引的注意事項(xiàng)詳解
在數(shù)據(jù)量超大的情形下,任何數(shù)據(jù)庫(kù)系統(tǒng)在創(chuàng)建索引時(shí)都是一個(gè)耗時(shí)的大工程,下面這篇文章主要給大家介紹了關(guān)于MongoDB排序時(shí)內(nèi)存大小限制與創(chuàng)建索引的注意事項(xiàng)的相關(guān)資料,需要的朋友可以參考下2022-05-05springboot + mongodb 通過(guò)經(jīng)緯度坐標(biāo)匹配平面區(qū)域的方法
這篇文章主要介紹了springboot + mongodb 通過(guò)經(jīng)緯度坐標(biāo)匹配平面區(qū)域的方法,文中通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10mongodb中按天進(jìn)行聚合查詢的實(shí)例教程
這篇文章主要給大家介紹了關(guān)于mongodb中按天進(jìn)行聚合查詢的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用mongodb具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07SpringBoot系列之MongoDB?Aggregations用法詳解
MongoDB?中使用聚合(Aggregations)來(lái)分析數(shù)據(jù)并從中獲取有意義的信息,本文重點(diǎn)給大家介紹SpringBoot系列之MongoDB?Aggregations用法,感興趣的朋友跟隨小編一起看看吧2022-02-02