使用Golang連接MongoDB方法詳解
MongoDB Driver For Golang
Golang連接MongoDB的庫有很多,本文主要講解使用MongoDB官方驅(qū)動(dòng)
go.mongodb.org/mongo-driver/mongo 連接MongoDB的方法。
支持使用URI類型的字符串連接MongoDB,字符串格式支持兩種類型:
- 標(biāo)準(zhǔn)連接字符串格式
- DNS種子列表連接格式
接下來以標(biāo)準(zhǔn)連接字符串格式來做講解。
使用Golang連接MongoDB
首先講下標(biāo)準(zhǔn)連接字符串格式URI,格式為:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
通過上篇文章《一文了解MongoDB的各種部署模式》我們知道Golang有幾種不同的部署方式,不同的部署方式對(duì)應(yīng)的URI也有些不同。
單節(jié)點(diǎn)(standalone)模式的格式為:
mongodb://username:password@mongodb0.example.com:27017
副本集模式的格式為:
mongodb://username:password@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl
對(duì)于副本集模式,需要指定副本集配置中列出的mongod實(shí)例的主機(jī)名,還需要指定replicaSet選項(xiàng)。
分片集群模式的格式為:
mongodb://username:password@mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017
不管哪種模式,如果用戶名或密碼包含如下字符:
: / ? # [ ] @
必須將這些字符轉(zhuǎn)換為百分比編碼。
獲取 mongo-driver/mongo 包:
go get go.mongodb.org/mongo-driver/mongo
示例代碼如下:
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// 這里uri使用副本集模式,如果你的MongoDB是其他模式,改為上面其他模式的uri即可
uri := os.Getenv("mongodb://username:password@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl")
opts := options.Client().ApplyURI(uri)
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
panic(err)
}
coll := client.Database("sample_mflix").Collection("movies")
title := "Back to the Future"
var result bson.M
err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&result)
if err == mongo.ErrNoDocuments {
fmt.Printf("No document was found with the title %s\n", title)
return
}
if err != nil {
panic(err)
}
jsonData, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", jsonData)
}
也可以設(shè)置連接池的最大和最小連接數(shù),示例代碼如下:
opts := options.Client().ApplyURI(uri)
opts.MaxPoolSize = 20
opts.MinPoolSize = 10