Reputation: 131
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
Reputation: 264
Working for MongoID 5.x. With the mongo shell and MongoID is straightforward:
Pick up your object id
ModelName.first.id # then copy your_id
Run mongo console
mongo
Get the size in bytes of the document
Object.bsonsize(db.modelname.find({"_id": ObjectId("your_id")}))
Upvotes: -1
Reputation: 2558
Solution for 2015 and mongoid (4.0.2):
model_instance.as_document.to_bson.size
Upvotes: 7
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
Reputation: 19213
This works for Mongoid 3.1.0:
model.as_document.__bson_dump__.size
Upvotes: 0
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