2

I was wondering what the Java driver's equivalent to the Mongo JavaScript shell's Object.bsonsize( doc ) method? For example, what is the Java code to perform 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 do I perform this same basic use case with the MongoDB Java Driver. Its not obvious through the JavaDocs.

3 Answers 3

6

There's nothing quite as clean as what's available in the shell, but this will work:

DBObject obj = coll.findOne();
int bsonSize = DefaultDBEncoder.FACTORY.create().
        writeObject(new BasicOutputBuffer(), obj));
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. That is long winded, and I can't resolve any DefaultDBEncoder in my IDE using Mongo 2.6.5 Java driver. Its also undesirable to have to write the document to figure out its size. My actual use case is I'm trying to enforce some size limits before I commit a document to the database. In any event, thanks for the reply and I'll see if I can get there from here.
@jyemin Using mongodb shell using Object.bsonSize getting as 390 where as using above we are getting as 386. is there any possibility to get exact size of the mongodb document
3

You can use BasicBSONEncoder:

DBObject obj = coll.findOne();
int bsonSize = new BasicBSONEncoder().encode(obj).length;

Comments

1

What about:

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

It's double instead of int.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.