mongodb java driver 3.0: how to store JSON document
Asked Answered
S

2

13

Looks basic and simple: A have a JSON string and I want to store it in MongoDB as JSON document.

In java driver 2.xx I could use com.mongodb.util.JSON.parse(String jsonString) to get DBObject and then store it in collection.

In driver 3.0 JSON.parse still gives DBObject, but rest of API uses org.bson.Document class which looks as incompatible with DBObject.

How to do it in driver version 3.0?

Slapbang answered 14/4, 2015 at 18:18 Comment(0)
A
28

For Document use the parse() static helper:

Document myDoc = Document.parse(jsonString)
Argumentum answered 15/4, 2015 at 10:28 Comment(2)
How could I miss it? Thank you :)Slapbang
Hi. I couldn't find a method for json arrays. using this method with json array string throws an exception.Gregggreggory
J
1

For you problem, you have at least 3 solutions, lets see:

private Map<String, Object> map;

private DBObject dbObject = new BasicDBObject(map);

private Document document = Document.parse(jsonText);

The imports of objects are:

import java.util.Map;
import org.bson.Document;
import com.mongodb.DBObject;

There are a difference with Document object, by default it disconsider all null attributes when object is persisted on mongo. The same not ocorres with another two, in your configuration default not.

I hope helped you...

Jat answered 30/4, 2020 at 12:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.