dongsu1951 2016-09-26 08:20 采纳率: 0%
浏览 176
已采纳

需要帮助使用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 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>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块