登录
首页 >  Golang >  Go问答

在 MongoDB 驱动程序中执行存储和检索操作

来源:stackoverflow

时间:2024-02-22 13:03:25 465浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在 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 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}}}

到这里,我们也就讲完了《在 MongoDB 驱动程序中执行存储和检索操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>