douhui4831
2015-12-24 06:07
浏览 753

如何在Golang中将json对象数组插入mongodb

My json looks like the following,

[
  {
    "key1": 1,
    "key2": "val2"
  },
  {
    "key1": 2,
    "key2": "val2"
  }
]

This json comes in string format and I want the objects in the json array to be inserted as individual records in mongodb. I referred to https://labix.org/mgo but wasn't able to find enough examples on the above use-case. Appreciate your thoughts in finding a solution.

图片转代码服务由CSDN问答提供 功能建议

我的json如下所示,

  [
  {
“ key1”:1,
“ key2”:“ val2” 
},
 {
“ key1”:2,
“ key2”:“ val2” 
} 
] 
    
 
 

此json为字符串格式,我希望将json数组中的对象作为单独的记录插入mongodb中。 我提到了 https://labix.org/mgo ,但找不到上述用法的足够示例 -案件。 感谢您在寻找解决方案时的想法。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • douyan8413 2015-12-24 17:22
    最佳回答

    Unmarshal the JSON to []interface{} and insert the result in the database. Assuming that c is an mgo.Collection and data is a []byte containing the JSON value, use the following code:

    var v []interface{}
    if err := json.Unmarshal(data, &v); err != nil {
       // handle error
    }
    if err := c.Insert(v...); err != nil {
       // handle error
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题