Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

MongoDB JSON to Document/DBObject

MongoDB integrates with JSON very well, but how to convert JSON to Document/DBObject using MongoDB API? In this post we show two solutions.

Conversion between JSON and Document/DBObject is especially useful during testing, when we export some documents from MongoDB as JSON and want to load in tests to perform computations.

MongoDB 3 – JSON to Document

Since MongoDB 3 the API is different and the basic class is org.bson.Document. To convert JSON into Document we can use Document.parse(String) like so:

String json = "{$match: {\"country\": {$in: [\"PL\"]}}}";
Document doc = Document.parse(json);

Document match = doc.get("$match", Document.class);
System.out.printf("$match: '%s'%n", match);

When run, the above code produces the following output:

$match: 'Document{{country=Document{{$in=[PL]}}}}'

As you can see, inner documents are also represented as Document objects.

MongoDB – JSON to DBObject

If you are still using the old MongoDB API and want to convert JSON to DBObject, then you can use JSON.parse(String) from com.mongodb.util package. The old API is less convenient, because it returns Object everywhere and you have to cast result to DBObject, but it gets the job done:

String json = "{$match: {\"country\": {$in: [\"PL\"]}}}";
DBObject dbObject = (DBObject) JSON.parse(json);

DBObject match = (DBObject) dbObject.get("$match");
System.out.printf("$match: '%s'%n", match);

The printed representation of DBObject is quite different than of Document, but that’s how it is in life. ;-)

$match: '{ "country" : { "$in" : [ "PL"]}}'
Share with the World!