dongsu1951
dongsu1951
2016-09-26 08:20
浏览 138

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

I m in the process of creating application where my back end is in go lang and database is mongoDB. My problem is that i have a map in my struct declared like

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

after adding values in to this like

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

I m inserting it like

c.Insert(&data)

When i insert this i m losing my key and can only see the values...

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

}

May i know any way possible to use interface and get both key and values in my mongoDB. Thanks....

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhi9457
    dongzhi9457 2016-09-26 10:37
    已采纳

    You can use nothing but string as key in MongoDB documents. Even if you would define your Data structure as map[int]interface{} Mongo (don't know if mgo will convert types) wouldn't allow you to insert this object into the database. Actually, you can use nothing but string as JSON key at all as this wouldn't be JSON (try in your browser console the next code JSON.parse('{2:"number"}')).

    So define your Data as bson.M (shortcut for map[string]interface{}) and use strconv package to convert your numbers into strings.

    But I guess you must look at arrays/slices, as only one reason why someone may need to have numbers as keys in JSON is iterations through these fields in future. And for iterations we use arrays.

    Update: just checked how mgo deals with map[int]interface{}. It inserts into DB entry like {"<int Value>" : "hello"}. Where <int Value> is not number but actually string <int Value>

    点赞 评论

相关推荐