Tom Johnson
Tom Johnson

Reputation: 131

Determine size of a document using Mongoid

Is there a method to determine the size of a specific instance of a model/document in a MongoDB using Mongoid?

Upvotes: 10

Views: 7816

Answers (5)

Rendrum
Rendrum

Reputation: 264

Working for MongoID 5.x. With the mongo shell and MongoID is straightforward:

  1. Pick up your object id

    ModelName.first.id # then copy your_id

  2. Run mongo console

    mongo

  3. Get the size in bytes of the document

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

Upvotes: -1

Alexander
Alexander

Reputation: 2558

Solution for 2015 and mongoid (4.0.2):

model_instance.as_document.to_bson.size

Upvotes: 7

Agung Prasetyo
Agung Prasetyo

Reputation: 4483

For mongoid 3.x you can use Moped::BSON::Document

for example :

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

Upvotes: -1

kizzx2
kizzx2

Reputation: 19213

This works for Mongoid 3.1.0:

model.as_document.__bson_dump__.size

Upvotes: 0

Gates VP
Gates VP

Reputation: 45277

So you can get the theoretical size of the document as you illustrated in your comment (BSON.serialize(Model.first.as_document).size).

However, it should be noted that this may not be the actual size of the object "on disk". MongoDB will automatically add a buffer to new documents to allow them to grow in-place. When it comes to getting the actual size on disk for one specific document I do not believe this is possible.

However, you can get an average buffer by using db.collection_name.stats().

Upvotes: 8

Related Questions