The explicit Java equivalent for JavaScript Object.bsonsize (doc)?

I was wondering if the Java driver is equivalent to the Mongo JavaScript method for Object.bsonsize (doc)? For example, what is Java code to do the following:

bobk-mbp:~ bobk$ mongo MongoDB shell version: 2.0.4 connecting to: test PRIMARY> use devices; switched to db devices PRIMARY> Object.bsonsize( db.profiles.findOne( { _id: "REK_0001" } ) ); 186 PRIMARY> Object.bsonsize( db.profiles.findOne( { _id: "REK_0002" } ) ); 218 PRIMARY> 

How to execute the same basic usage example with the MongoDB Java driver. This is not obvious through JavaDocs.

+2
mongodb mongodb-java
source share
3 answers

There is nothing as clean as what is available in the shell, but this will work:

 DBObject obj = coll.findOne(); int bsonSize = DefaultDBEncoder.FACTORY.create(). writeObject(new BasicOutputBuffer(), obj)); 
+6
source share

You can use BasicBSONEncoder :

 DBObject obj = coll.findOne(); int bsonSize = new BasicBSONEncoder().encode(obj).length; 
+3
source share

What about:

  CommandResult result = db.doEval("Object.bsonsize(db.profiles.findOne({ _id: "REK_0001" }))"); double bsonSize = (Double) result.get("retval"); 

It is double, not int.

doEval is part of the MongoDB Java driver since the first version.

+1
source share

All Articles