Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo convert Document to DBObject

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 ?

like image 442
František Jeřábek Avatar asked Sep 13 '17 07:09

František Jeřábek


People also ask

How do I convert a file to DBObject in Java?

However, since both classes are implementations of Map, you can just do: Document document = new Document(); BasicDBObject basicDBObject = new BasicDBObject(document);

How do I convert DBObject to JSON?

JSON” class to convert JSON data directly to a DBObject. To convert it to DBObject, you can code like this : DBObject dbObject = (DBObject) JSON. parse("{"empName" : "Dinesh Rajput", "empAge" : 26, "salary" : 70000}");

What is BasicDBObject in Java?

public BasicDBObject(String key, Object value) Creates an object with the given key/value. Parameters: key - key under which to store value - value to store.


2 Answers

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.

like image 145
Luciano van der Veekens Avatar answered Nov 16 '22 04:11

Luciano van der Veekens


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());
    }
}
like image 28
phoenix7360 Avatar answered Nov 16 '22 02:11

phoenix7360