首页 > 后端开发 > Golang > 正文

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

PHPz
发布: 2024-02-06 09:39:07
转载
1211人浏览过

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 a> 只是一个 [] 接口{},并且 bson.dbson.a 其中 e

type e struct {
    key   string
    value interface{}
}
登录后复制

所以基本上 [] 接口{}键值对(属性)的有序列表。

因此,当您使用 bson.d 时,您会得到一片切片,而不是多个地图。不打印类型信息,[]e 包打印切片和地图,两者都括在方括号中。

如果您想查看类型,请像这样打印:

fmt.printf("%#v\n", result.data)
登录后复制

使用e时的输出:

[]map[string]interface {}{map[string]interface {}{"key1":"using specific type", "key2":123}}
登录后复制

使用 bson.d 时的输出:

primitive.A{primitive.D{primitive.E{Key:"key1", Value:"using specific type"}, primitive.E{Key:"key2", Value:123}}}
登录后复制

以上就是mongogo 驱动程序中的 Mongodb 存储和检索的详细内容,更多请关注php中文网其它相关文章!

驱动精灵
驱动精灵

驱动精灵基于驱动之家十余年的专业数据积累,驱动支持度高,已经为数亿用户解决了各种电脑驱动问题、系统故障,是目前有效的驱动软件,有需要的小伙伴快来保存下载体验吧!

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号