go 操作 mongodb

MongoDB Go驅(qū)動(dòng)程序

MongoDB Go Driver使用幫助文檔

安裝使用:

go.mongodb.org/mongo-driver/mongo

安裝直接 go mod 就 ok了

使用Go Driver連接到MongoDB

1、鏈接數(shù)據(jù)庫(kù) mongo.Connect()
Connect 需要兩個(gè)參數(shù),一個(gè)context和一個(gè)options.ClientOptions對(duì)象
簡(jiǎn)單的鏈接實(shí)例:

// 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!")

上面代碼的流程就是 創(chuàng)建 鏈接對(duì)象 option 和 context , 然后寫入mongo.Connect , Connect 函數(shù)返回一個(gè)鏈接對(duì)象 和一個(gè)錯(cuò)誤 對(duì)象,如果錯(cuò)誤對(duì)象不為空,那就鏈接失敗了
然后我們可以再次測(cè)試,鏈接:client.Ping(context.TODO(), nil)
cilent 對(duì)象 Ping 就好了,他會(huì)返回一個(gè)錯(cuò)誤對(duì)象,如果不為空,就鏈接失敗了
2、鏈接成功后,可以創(chuàng)建 數(shù)據(jù)表的鏈接對(duì)象了:

collection := client.Database("test").Collection("aaa")

test 是數(shù)據(jù)庫(kù),aaa是數(shù)據(jù)表
3、斷開鏈接對(duì)象 client.Disconnect()
如果我們不在使用 鏈接對(duì)象,那最好斷開,減少資源消耗

err = client.Disconnect(context.TODO())
if err != nil {
    log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
操作數(shù)據(jù)庫(kù)

使用 bson 結(jié)構(gòu)來(lái)傳遞命令,mongo 保存的數(shù)據(jù)是 json 的二進(jìn)制形式,此外還擴(kuò)展 了數(shù)據(jù)類型,可以表示 int, array 等字段類型。
Go Driver有兩個(gè)系列的類型表示BSON數(shù)據(jù):D系列類型和Raw系列類型
既然文檔只講了 D系列,那就先看 D

– D:一個(gè)BSON文檔。這個(gè)類型應(yīng)該被用在順序很重要的場(chǎng)景, 比如MongoDB命令。
– M: 一個(gè)無(wú)需map。 它和D是一樣的, 除了它不保留順序。
– A: 一個(gè)BSON數(shù)組。
– E: 在D里面的一個(gè)單一的子項(xiàng)。

M (map) A(array) 其他兩個(gè)不知啥縮寫。

bson.D{{
    "name", 
    bson.D{{
        "$in", 
        bson.A{"Alice", "Bob"}
    }}
}}

上面是一個(gè)簡(jiǎn)單的過濾文檔,匹配的是 name 是Alice 或 Bob的數(shù)據(jù)

CRUD操作

明天看吧》》》
和 pymongo 基本是兄弟

  • 插入單個(gè)文檔
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()

不同的是接受一個(gè) 切片作為數(shù)據(jù)集合

trainers := []interface{}{misty, brock}

insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
  • 更新文檔
    更新單個(gè)文檔
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"}}  // 不推薦直
接用結(jié)構(gòu)體,玩意結(jié)構(gòu)體字段多了,初始化為零值。
// 因?yàn)榭赡軙?huì)吧零值更新到數(shù)據(jù)庫(kù),而不是像 gorm 的updates 忽略零值
  • 查找文檔
    需要一個(gè)filter文檔, 以及一個(gè)指針在它里邊保存結(jié)果的解碼
    查詢單個(gè)文檔:
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)

查詢多個(gè)文檔使用:

collection.Find()

查詢多個(gè)文檔事例:

one, _:= collect.Find(context.TODO(), bson.M{"task_id": "cccccc"})

    defer func() {  // 關(guān)閉
        if err := one.Close(context.TODO()); err != nil {
            log.Fatal(err)
        }
    }()

    c := []server.Task_info{}
    _ = one.All(context.TODO(), &c)   // 當(dāng)然也可以用   next
    for _, r := range c{
        Println(r)
    }
  • 刪除文檔
collection.DeleteOne() 或者 collection.DeleteMany()

bson.D{{}}作為filter參數(shù),這會(huì)匹配集合內(nèi)所有的文檔

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")  // 拿到數(shù)據(jù)表 
ind, err = collect.Indexes().CreateOne(context.TODO(), mod)  // returns (string, error)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。