安裝使用:
go.mongodb.org/mongo-driver/mongo
安裝直接 go mod 就 ok了
使用Go Driver連接到MongoDB
1、鏈接數據庫 mongo.Connect()
Connect 需要兩個參數,一個context和一個options.ClientOptions對象
簡單的鏈接實例:
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
上面代碼的流程就是 創建 鏈接對象 option 和 context , 然后寫入mongo.Connect , Connect 函數返回一個鏈接對象 和一個錯誤 對象,如果錯誤對象不為空,那就鏈接失敗了
然后我們可以再次測試,鏈接:client.Ping(context.TODO(), nil)
cilent 對象 Ping 就好了,他會返回一個錯誤對象,如果不為空,就鏈接失敗了
2、鏈接成功后,可以創建 數據表的鏈接對象了:
collection := client.Database("test").Collection("aaa")
test 是數據庫,aaa是數據表
3、斷開鏈接對象 client.Disconnect()
如果我們不在使用 鏈接對象,那最好斷開,減少資源消耗
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
操作數據庫
使用 bson 結構來傳遞命令,mongo 保存的數據是 json 的二進制形式,此外還擴展 了數據類型,可以表示 int, array 等字段類型。
Go Driver有兩個系列的類型表示BSON數據:D系列類型和Raw系列類型
既然文檔只講了 D系列,那就先看 D
– D:一個BSON文檔。這個類型應該被用在順序很重要的場景, 比如MongoDB命令。
– M: 一個無需map。 它和D是一樣的, 除了它不保留順序。
– A: 一個BSON數組。
– E: 在D里面的一個單一的子項。
M (map) A(array) 其他兩個不知啥縮寫。
bson.D{{
"name",
bson.D{{
"$in",
bson.A{"Alice", "Bob"}
}}
}}
上面是一個簡單的過濾文檔,匹配的是 name 是Alice 或 Bob的數據
CRUD操作
明天看吧》》》
和 pymongo 基本是兄弟
- 插入單個文檔
collection.InsertOne()
type Trainer struct {
Name string
Age int
City string
}
ash := Trainer{"Ash", 10, "Pallet Town"}
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
- 插入多條文檔
collection.InsertMany()
不同的是接受一個 切片作為數據集合
trainers := []interface{}{misty, brock}
insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
-
更新文檔
更新單個文檔
collection.UpdateOne()
filter := bson.D{{"name", "Ash"}}
update := bson.D{
{"$inc", bson.D{
{"age", 1},
}},
}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
// update := bson.M{"$set": server.Task_info{Task_id: "update task id"}} // 不推薦直
接用結構體,玩意結構體字段多了,初始化為零值。
// 因為可能會吧零值更新到數據庫,而不是像 gorm 的updates 忽略零值
-
查找文檔
需要一個filter文檔, 以及一個指針在它里邊保存結果的解碼
查詢單個文檔:
collection.FindOne()
var result Trainer
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
查詢多個文檔使用:
collection.Find()
查詢多個文檔事例:
one, _:= collect.Find(context.TODO(), bson.M{"task_id": "cccccc"})
defer func() { // 關閉
if err := one.Close(context.TODO()); err != nil {
log.Fatal(err)
}
}()
c := []server.Task_info{}
_ = one.All(context.TODO(), &c) // 當然也可以用 next
for _, r := range c{
Println(r)
}
- 刪除文檔
collection.DeleteOne() 或者 collection.DeleteMany()
bson.D{{}}作為filter參數,這會匹配集合內所有的文檔
deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
為字段建立索引
mod := mongo.IndexModel{
Keys: bson.M{
"Some Int": -1, // index in descending order
},
// create UniqueIndex option
Options: options.Index().SetUnique(true),
}
// Create an Index using the CreateOne() method
collect = some_database.Collection("xxx") // 拿到數據表
ind, err = collect.Indexes().CreateOne(context.TODO(), mod) // returns (string, error)