【问题标题】:How to get size in bytes of bson documents如何以字节为单位获取 bson 文档的大小
【发布时间】:2015-12-31 11:08:30
【问题描述】:

bson文档的size()函数返回的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 的大小

标签: mongodb mongodb-java bson


【解决方案1】:

如果您需要知道对象在集合中之前的大小,我使用了以下代码,其中 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/

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 使用 ByteBuf.capacity() 不正确。改用 ByteBuf.remaining()。容量是包装后的字节数组的大小,可能比实际文档大。使用 ByteBuf.remaining() 会告诉你有多少字节被文档实际占用。
    • @jyemin 是对的,我将剩余的结果与容量进行了比较,对我来说容量更大,剩余与 Mongo shell 的 bsonsize 函数的输出相匹配。
    猜你喜欢
    • 2016-04-18
    • 2013-02-01
    • 2012-02-17
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多