首頁 > 後端開發 > Golang > 主體

mongogo 驅動程式中的 Mongodb 儲存和檢索

PHPz
發布: 2024-02-06 09:39:07
轉載
1003 人瀏覽過

mongogo 驱动程序中的 Mongodb 存储和检索

問題內容

我正在嘗試插入資料並使用 mongo go 驅動程式從 mongodb 讀取該資料。我正在使用一個具有資料欄位的結構。當我使用資料類型作為介面時,我會得到多個映射,當我將其指定為映射切片時,它會傳回單一映射。 mongodb 中的資料類似。

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Host struct {
    Hostname string                   `bson:"hostname"`
    Data     []map[string]interface{} `bson:"data"` //return single map
    // Data     interface{} `bson:"data"` //returns multiple maps

}

func main() {
    // Set up a MongoDB client
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        panic(err)
    }

    // Set up a MongoDB collection
    collection := client.Database("testdb").Collection("hosts")

    // Create a host object to insert into the database
    host := Host{
        Hostname: "example.com",
        Data: []map[string]interface{}{
            {"key1": "using specific type", "key2": 123},
        },
    }

    // Insert the host object into the collection
    _, err = collection.InsertOne(context.Background(), host)
    if err != nil {
        panic(err)
    }

    // Query the database for the host object
    filter := bson.M{"hostname": "example.com"}
    var result Host
    err = collection.FindOne(context.Background(), filter).Decode(&result)
    if err != nil {
        panic(err)
    }

    // Print the host object
    fmt.Println(result)
}
登入後複製

僅使用介面時

當使用地圖切片時

兩種情況下儲存的資料相似。

為什麼當我們嘗試存取資料時會出現資料差異?


正確答案


當您使用interface{} 時,這表示您將由驅動程式來選擇它認為最能代表從mongodb到達的資料的任何資料類型。

當您使用 []map[string]interface{} 時,您明確表示您想要一個地圖切片,其中每個地圖可以代表一個文件。

當您使用 interface{} 時,您什麼也不說。驅動程式將選擇 bson.a 來表示數組,並選擇 bson.d 來表示文件。

bson.a 只是一個[] 介面{},並且bson.d []e 其中e

type e struct {
    key   string
    value interface{}
}
登入後複製

所以基本上 bson.d 是鍵值對(屬性)的有序列表。

因此,當您使用 interface{} 時,您會得到一片切片,而不是多個地圖。不列印類型訊息,fmt 套件列印切片和地圖,兩者都括在方括號中。

如果您想查看類型,請像這樣列印:

fmt.printf("%#v\n", result.data)
登入後複製

使用[]map[string]介面{}時的輸出:

[]map[string]interface {}{map[string]interface {}{"key1":"using specific type", "key2":123}}
登入後複製

使用 interface{} 時的輸出:

primitive.A{primitive.D{primitive.E{Key:"key1", Value:"using specific type"}, primitive.E{Key:"key2", Value:123}}}
登入後複製

以上是mongogo 驅動程式中的 Mongodb 儲存和檢索的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!