javascript – Mongo = get size of single document-ThrowExceptions

Exception or error:

I encountered a strange behavior of mongo and I would like to clarify it a bit…
My request is simple as that: I would like to get a size of single document in collection.
I found two possible solutions:

  • Object.bsonsize – some javascript method that should return a size in bytes
  • db.collection.stats() – where there is a line ‘avgObjSize’ that produce some “aggregated”(average) size view on the data. It simply represents average size of single document.
  • When I create test collection with only one document, both functions returns different values. How is it possible?
    Does it exist some other method to get a size of a mongo document?

Here, I provide some code I perform testing on:

  1. I created new database ‘test’ and input simple document with only one attribute: type:”auto”

  2. output from stats() function call: db.test.stats():

      "ns" : "test.test",
      "count" : 1,
      "size" : 40,
      "avgObjSize" : 40,
      "storageSize" : 4096,
      "numExtents" : 1,
      "nindexes" : 1,
      "lastExtentSize" : 4096,
      "paddingFactor" : 1,
      "systemFlags" : 1,
      "userFlags" : 0,
      "totalIndexSize" : 8176,
      "indexSizes" : {
            "_id_" : 8176
    "ok" : 1


  3. output from bsonsize function call: Object.bsonsize(db.test.find({test:”auto”}))

How to solve:

I have found a solution. In the previous call of Object.bsonsize mongo returned size OF THE CURSOR rather than the document itself.

Correct way is to use this command:


this will return the correct size of the particular document (in bytes).


The effective amount of space the document will take in the collection will be more than the size of your document because of the Record Padding mechanism.

This is why there is a difference between the outputs of the db.test.stats() and Object.bsonsize(..).

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


I recommended to use this script to get the real size.

  var size = Object.bsonsize(obj);
  print('_id: '+obj._id+' || Size: '+size+'B -> '+Math.round(size/(1024))+'KB -> '+Math.round(size/(1024*1024))+'MB (max 16MB)');

Note: If your IDs are 64-bit integers, the above will truncate the ID value on printing! If that’s the case, you can use instead:

  var size = Object.bsonsize(obj);
  var stats =
    '_id': obj._id, 
    'bytes': size, 
    'KB': Math.round(size/(1024)), 
    'MB': Math.round(size/(1024*1024))

This also has the advantage of returning JSON, so a GUI like RoboMongo can tabulate it!

source :

edit : thanks to @zAlbee for your suggest completion.


It gives in bytes.

Leave a Reply

Your email address will not be published. Required fields are marked *