Java driver equivalent for JavaScript shell's Object.bsonsize( doc )?

时光毁灭记忆、已成空白 提交于 2019-12-07 20:05:15

问题


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.


回答1:


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));



回答2:


You can use BasicBSONEncoder:

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



回答3:


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.



来源:https://stackoverflow.com/questions/10885794/java-driver-equivalent-for-javascript-shells-object-bsonsize-doc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!