公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

问题内容

我正在尝试插入数据并使用 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}}}

登录后复制

分享到:
标签:键值对
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定