首页 > 后端开发 > 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.a 只是一个 [] 接口{},并且 bson.d[]e 其中 e

type e struct {
    key   string
    value interface{}
}
登录后复制
bson.d所以基本上

是键值对(属性)的有序列表。

interface{} 时,您会得到一片切片,而不是多个地图。不打印类型信息,fmt因此,当您使用

时,您会得到一片切片,而不是多个地图。不打印类型信息,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学习者快速成长!