Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal json string to bson document for writing to MongoDB?

Tags:

mongodb

go

mgo

What I am looking is equivalent of Document.parse()

in golang, that allows me create bson from json directly? I do not want to create intermediate Go structs for marshaling

like image 786
Ganesh Avatar asked Sep 30 '16 06:09

Ganesh


People also ask

Does MongoDB convert JSON to BSON?

Does MongoDB use BSON, or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.

How do you Unmarshal BSON?

You can unmarshal BSON documents by using the Decode() method on the result of the FindOne method or any *mongo.

How do I parse a BSON document?

BSON documents are lazily parsed as necessary. To begin parsing a BSON document, use one of the provided Libbson functions to create a new bson_t from existing data such as bson_new_from_data(). This will make a copy of the data so that additional mutations may occur to the BSON document.

How do I create a BSON file?

bson. Document; final Document doc = new Document("myKey", "myValue"); final String jsonString = doc. toJson(); final Document doc = Document. parse(jsonString);


1 Answers

The gopkg.in/mgo.v2/bson package has a function called UnmarshalJSON which does exactly what you want.

The data parameter should hold you JSON string as []byte value.

 func UnmarshalJSON(data []byte, value interface{}) error

UnmarshalJSON unmarshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.

Example:

var bdoc interface{}
err = bson.UnmarshalJSON([]byte(`{"id": 1,"name": "A green door","price": 12.50,"tags": ["home", "green"]}`),&bdoc)
if err != nil {
    panic(err)
}
err = c.Insert(&bdoc)

if err != nil {
    panic(err)
}
like image 148
TheHippo Avatar answered Sep 24 '22 06:09

TheHippo