Mongo convert Document to DBObject

František Jeřábek :

Hi I need to convert Mongo Document to DBObject (BasicDBObject).

I am uploading a file to mongo using GridFS and I want to set metadata, which I get in document. I know Document is pretty much the same as DBObject. I know I can do something like this:

Document doc = new Document();
BasicDBObject.parse(doc.toJson());

But isn't this needlessly performance heavy?

The gridFS method setMetaData() accepts only DBObject so i have to convert it.

Is there a better way of doing that rather then converting it to string and back ?

Luciano van der Veekens :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466104&siteId=1