Is there a method to determine the size of a specific instance of a model/document in a MongoDB using Mongoid?
To get the exact size (in bytes) of the document, stick to the Object. bsonsize() function.
Document Size Limit The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
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()
.
Solution for 2015 and mongoid (4.0.2):
model_instance.as_document.to_bson.size
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With