Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
Tom Johnson Avatar asked Jan 07 '12 22:01

Tom Johnson


People also ask

How do I find the size of a document in MongoDB?

To get the exact size (in bytes) of the document, stick to the Object. bsonsize() function.

What is document size in MongoDB?

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.

How do I search in MongoDB?

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.


2 Answers

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

like image 178
Gates VP Avatar answered Oct 07 '22 00:10

Gates VP


Solution for 2015 and mongoid (4.0.2):

model_instance.as_document.to_bson.size
like image 42
Alexander Karmes Avatar answered Oct 07 '22 00:10

Alexander Karmes