2012-01-07 41 views
8

有沒有一種方法來確定使用Mongoid的MongoDB中模型/文檔的特定實例的大小?使用Mongoid確定文檔的大小

+0

我居然想出了一個解決方案,以獲得某個文檔的字節數: 'BSON.serialize(Model.first.as_document).size' – 2012-01-07 22:26:07

回答

7

因此,您可以獲得文檔的理論大小,如您在評論中所示(BSON.serialize(Model.first.as_document).size)所示。

但是,應該注意的是,這可能不是「磁盤上」對象的實際大小。 MongoDB會自動爲新文檔添加一個緩衝區,以允許它們就地增長。當談到爲一個特定的文件獲取磁盤的實際大小時,我不認爲這是可能的。

但是,您可以使用db.collection_name.stats()獲得平均緩衝區。

+1

這似乎不是一起工作Mongoid 3.x更多。 – 2012-12-04 20:37:00

0

這適用於Mongoid 3.1.0:

model.as_document.__bson_dump__.size 
-1

對於mongoid 3.x中,你可以使用助力車:: BSON ::文件

例如:

your_document = Model.find(id) 
# get size 
size = Moped::BSON::Document.serialize(your_document.as_document).size 
5

解決方案2015和mongoid(4.0.2):

model_instance.as_document.to_bson.size 
0

W請求MongoID 5.x.隨着蒙戈外殼和MongoID很簡單:

  1. 拿起你的對象ID

    ModelName.first.id # then copy your_id

  2. 運行蒙戈控制檯

    mongo

  3. 獲取的字節大小文件

    Object.bsonsize(db.modelname.find({"_id": ObjectId("your_id")}))