需要帮助使用 golang 在我的 mongodb 数据库中存储类型接口的映射

Need help to storing an map of type interface in my mongodb database using golang

我正在创建应用程序,我的后端在 go lang 中,数据库是 mongoDB。我的问题是我的结构中有一个地图声明为

Data struct {
        data   map[interface{}]interface{}
}

在像这样添加值后

var data Data
    data["us"]="country"
    data[2]="number"
    data["mother"]="son"

我想插入它

c.Insert(&data)

当我插入这个时,我丢失了我的密钥并且只能看到值...

{
    "_id" : Object Id("57e8d9048c1c6f751ccfaf50"),
    "data" : {
        "<interface {} Value>" : "country",
        "<interface {} Value>" : "number",
        "<interface {} Value>" : "son"
    },

}

我可以知道任何可能的方式来使用界面并在我的 mongoDB 中获取键和值。谢谢....

您只能使用 string 作为 Mongo 数据库文档中的键。即使您将 Data 结构定义为 map[int]interface{} Mongo(不知道 mgo 是否会转换类型)也不允许您将此对象插入数据库.实际上,除了 string 之外你什么都不能用作为 JSON 键,因为这不会是 JSON(在你的浏览器控制台中尝试下一个代码 JSON.parse('{2:"number"}'))。

因此将您的 Data 定义为 bson.Mmap[string]interface{} 的快捷方式)并使用 strconv 包将您的数字转换为字符串。

但我想您必须看看 arrays/slices,因为有人可能需要将数字作为 JSON 中的键的唯一原因之一是将来通过这些字段进行迭代。对于迭代,我们使用数组。

更新:刚刚检查了 mgo 如何处理 map[int]interface{}。它像 {"<int Value>" : "hello"} 一样插入到数据库条目中。 <int Value> 不是数字,实际上是 string <int Value>