1. 程式人生 > 資料庫 >利用golang驅動操作MongoDB資料庫的步驟

利用golang驅動操作MongoDB資料庫的步驟

安裝MongoDB驅動程式

mkdr mongodb 
cd mongodb 
go mod init 
go get go.mongodb.org/mongo-driver/mongo

連線MongoDB

建立一個main.go檔案

將以下包匯入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]]

單機版

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物件,該物件用於設定連線字串和其他驅動程式設定。
通過context.TODO()表示不確定現在使用哪種上下文,但是會在將來新增一個

使用Ping方法來檢測是否已正常連線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)

列出所有資料庫

databases,err := client.ListDatabaseNames(ctx,bson.M{})
if err != nil {
 log.Fatal(err)
}
fmt.Println(databases)

在GO中使用BSON物件

MongoDB中的JSON文件以稱為BSON(二進位制編碼的JSON)的二進位制表示形式儲存。與其他將JSON資料儲存為簡單字串和數字的資料庫不同,BSON編碼擴充套件了JSON表示形式,例如int,long,date,float point和decimal128。這使應用程式更容易可靠地處理,排序和比較資料。Go Driver有兩種系列用於表示BSON資料:D系列型別和Raw系列型別。

D系列包括四種類型:

  • D:BSON文件。此型別應用在順序很重要的場景下,例如MongoDB命令。
  • M:無序map。除不保留順序外,與D相同。
  • A:一個BSON陣列。
  • E:D中的單個元素。

插入資料到MongoDB

插入單條文件

//定義插入資料的結構體
type sunshareboy struct {
Name string
Age int
City string
}
//連線到test庫的sunshare集合,集合不存在會自動建立
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)

執行結果如下

![](https://s4.51cto.com/images/blog/202011/07/378adacb26314b3532fa8947e3516fc1.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
#### 同時插入多條文件
```go
collection := client.Database("test").Collection("sunshare")
dongdong:=sunshareboy{"張鼕鼕",29,"成都"}
huazai:=sunshareboy{"華仔",28,"深圳"}
suxin:=sunshareboy{"素心","甘肅"}
god:=sunshareboy{"劉大仙","杭州"}
qiaoke:=sunshareboy{"喬克","重慶"}
jiang:=sunshareboy{"姜總","上海"}
//插入多條資料要用到切片
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中查詢資料

查詢單個文件

查詢單個文件使用collection.FindOne()函式,需要一個filter文件和一個可以將結果解碼為其值的指標

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)

返回結果如下

Connected to MongoDB!
Found a single document: {Name:wanger Age:24 City:北京}
Connection to MongoDB closed.

查詢多個文件

查詢多個文件使用collection.Find()函式,這個函式會返回一個遊標,可以通過他來迭代並解碼文件,當迭代完成後,關閉遊標

  • Find函式執行find命令並在集合中的匹配文件上返回Cursor。
  • filter引數必須是包含查詢運算子的文件,並且可以用於選擇結果中包括哪些文件。不能為零。空文件(例如bson.D {})應用於包含所有文件。
  • opts引數可用於指定操作的選項,例如我們可以設定只返回五條文件的限制(https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#Find)。
//定義返回文件數量
findOptions := options.Find()
findOptions.SetLimit(5)

//定義一個切片儲存結果
var results []*sunshareboy

//將bson.D{{}}作為一個filter來匹配所有文件
cur,err := collection.Find(context.TODO(),bson.D{{}},findOptions)
if err != nil {
 log.Fatal(err)
}
//查詢多個文件返回一個遊標
//遍歷遊標一次解碼一個遊標
for cur.Next(context.TODO()) {
 //定義一個文件,將單個文件解碼為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)
}
//遍歷結束後關閉遊標
cur.Close(context.TODO())
fmt.Printf("Found multiple documents (array of pointers): %+v\n",results)

返回結果如下

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文件

更新單個文件

更新單個文件使用collection.UpdateOne()函式,需要一個filter來匹配資料庫中的文件,還需要使用一個update文件來更新操作

  • filter引數必須是包含查詢運算子的文件,並且可以用於選擇要更新的文件。不能為零。如果過濾器不匹配任何文件,則操作將成功,並且將返回MatchCount為0的UpdateResult。如果過濾器匹配多個文件,將從匹配的集合中選擇一個,並且MatchedCount等於1。
  • update引數必須是包含更新運算子的文件(https://docs.mongodb.com/manual/reference/operator/update/),並且可以用於指定要對所選文件進行的修改。它不能為nil或為空。
  • opts引數可用於指定操作的選項。
filter := bson.D{{"name","張鼕鼕"}}
//如果過濾的文件不存在,則插入新的文件
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)
}

返回結果如下

Connected to MongoDB!
Matched 1 documents and updated 1 documents.
Connection to MongoDB closed.

更新多個文件

更新多個文件使用collection.UpdateOne()函式,引數與collection.UpdateOne()函式相同

filter := bson.D{{"city","北京"}}
//如果過濾的文件不存在,則插入新的文件
opts := options.Update().SetUpsert(true)
update := bson.D{
{"$set","鐵嶺"}},err := collection.UpdateMany(context.TODO(),result.UpsertedID)
}

返回結果如下

Connected to MongoDB!
Matched 2 documents and updated 2 documents.
Connection to MongoDB closed.

刪除MongoDB文件

可以使用collection.DeleteOne()或collection.DeleteMany()刪除文件。如果你傳遞bson.D{{}}作為過濾器引數,它將匹配資料集中的所有文件。還可以使用collection. drop()刪除整個資料集。

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)

返回結果如下

Connected to MongoDB!
Deleted 2 documents in the trainers collection
Connection to MongoDB closed.

獲取MongoDB服務狀態

上面我們介紹了對MongoDB的CRUD,其實還支援很多對mongoDB的操作,例如聚合、事物等,接下來介紹一下使用golang獲取MongoDB服務狀態,執行後會返回一個bson.Raw型別的資料

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

到此這篇關於利用golang驅動操作MongoDB資料庫的文章就介紹到這了,更多相關golang驅動操作MongoDB內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!