Mongo convert Document to DBObject
You are kind of micro-optimizing here.
However, since both classes are implementations of Map, you can just do:
Document document = new Document();
BasicDBObject basicDBObject = new BasicDBObject(document);
Internally this does a Map#putAll
operation that puts all entries of the Document map into the BasicDbObject map.
I know this is an old question and there is an accepted answer however it is not correct.
The proposed answer only does a shallow conversion between Document
and DBOject
. If your Json object contains nested objects or lists they will not be converted properly.
I got around this problem by serialising to JSON string. It is not efficient at all but might be enough in most cases, and at least it is correct:
public final class BsonConverter {
public static Document toDocument(DBObject dbObject) {
return Document.parse(dbObject.toString());
}
public static DBObject toDBObject(Document document) {
return BasicDBObject.parse(document.toJson());
}
}