How to get size in bytes of bson documents

痴心易碎 提交于 2019-12-23 21:19:48

问题


Is the int value returned by size() function of bson document the number of bytes ? (not able to find the details of this API).
How can I get the size of a bson document in bytes? Here is my code.

import org.bson.Document;

MongoDatabase db...;
MongoCollection<Document> mongoCollection = db.getCollection(...);
MongoCursor<Document> cursor = mongoCollection.find().iterator();
Document doc = cursor.next();
int size = doc.size(); // does this return number of bytes 
// how to get size of doc in bytes?

回答1:


Get the document as a RawBsonDocument then use the getByteBuffer().remaining() method.

MongoCollection<RawBsonDocument> mongoCollection = db.getCollection(collectionName, RawBsonDocument.class);
MongoCursor<RawBsonDocument> cursor = mongoCollection.find().iterator();
RawBsonDocument doc = cursor.next();
int size = doc.getByteBuffer().remaining()



回答2:


If you need to know the size the object will take before it is in the Collection, I used this code where o is the Object to test:

    BsonDocument bsonDocument = BsonDocumentWrapper.asBsonDocument(o, getMongoCollection().getCodecRegistry());
    RawBsonDocument rawBsonDocument = RawBsonDocument.parse(bsonDocument.toJson() );

    int bsonSize = rawBsonDocument.getByteBuffer().remaining();

This is particularly useful if you want to prevent objects that might be exceeding the maximum size of 16Mb: https://docs.mongodb.com/manual/reference/limits/



来源:https://stackoverflow.com/questions/34545555/how-to-get-size-in-bytes-of-bson-documents

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