问题
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