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

如何在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.

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

2条回答 默认 最新

  • douyan8413
    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
    }
    
    点赞 评论
  • du7133
    du7133 2019-07-23 18:09

    If you have json data already please follow from step 2.

    If you have Xml data first you need to convert to the json format by using this package("github.com/basgys/goxml2json")

     type JsonFileResponse struct {
        JsonData string        `bson:"JsonData " json:"JsonData"`
    }
    
    step 1: jsonData, err := xml2json.Convert(xml)
            if err != nil {
                panic("getting error while converting xml to json",err)
            }
    
    step 2: session need to open by using your mongodb credentials.
    
        collection := session.DB("database name").C("Collection Name")
        err = collection.Insert(JsonFileResponse{JsonData :json.String()})
        if err != nil {
            log.Fatal(err)
        } 
    
    点赞 评论

相关推荐