Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a json object array to mongodb in golang

Tags:

mongodb

go

mgo

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.

like image 586
Anuruddha Avatar asked Nov 25 '25 16:11

Anuruddha


1 Answers

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
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!