Search code examples
mongodbmongodb-javabson

How to get size in bytes of bson documents


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?

Solution

  • 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()