如何获取BSON文档的字节大小

3

size()函数返回的bson文档的int值是字节数吗?(无法找到此API的详细信息)。如何以字节为单位获取bson文档的大小?这是我的代码。

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?

@Magnus 寻找 org.bson.Document 的大小 - undefined
2个回答

4
如果您需要在对象加入集合之前知道其大小,可以使用以下代码进行测试,其中o是要测试的对象:
    BsonDocument bsonDocument = BsonDocumentWrapper.asBsonDocument(o, getMongoCollection().getCodecRegistry());
    RawBsonDocument rawBsonDocument = RawBsonDocument.parse(bsonDocument.toJson() );

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

如果您想防止可能超过16Mb最大大小的对象,这将特别有用:https://docs.mongodb.com/manual/reference/limits/


1
获取文档作为RawBsonDocument,然后使用getByteBuffer().remaining()方法。
MongoCollection<RawBsonDocument> mongoCollection = db.getCollection(collectionName, RawBsonDocument.class);
MongoCursor<RawBsonDocument> cursor = mongoCollection.find().iterator();
RawBsonDocument doc = cursor.next();
int size = doc.getByteBuffer().remaining()

4
使用ByteBuf.capacity()是错误的。应该使用ByteBuf.remaining()代替。容量是包装字节数组的大小,可能比实际文档大。使用ByteBuf.remaining()会告诉您实际上有多少字节被文档占用。 - undefined
@jyemin 是对的,我比较了剩余容量和总容量的结果,对我来说总容量更大,而剩余容量与Mongo shell中的bsonsize函数的输出相匹配。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接