How to get the size of single document in Mongodb?

In the previous call of Object.bsonsize(), Mongodb returned the size of the cursor, rather than the document.

Correct way is to use this command:

Object.bsonsize(db.test.findOne())

With findOne(), you can define your query for a specific document:

Object.bsonsize(db.test.findOne({type:"auto"}))

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


MAXIMUM DOCUMENT SIZE 16 MiB (source)


If you have version >=4.4 ($bsonSize source)

db.users.aggregate([
  {
    "$project": {
      "size_bytes": { "$bsonSize": "$$ROOT" },
      "size_KB": { "$divide": [{"$bsonSize": "$$ROOT"}, 1000] },
      "size_MB": { "$divide": [{"$bsonSize": "$$ROOT"}, 1000000] }
    }
  }
])

If you have version <4.4 (Object.bsonSize() source)

You can use this script for get a real size:

db.users.find().forEach(function(obj)
{
  var size = Object.bsonsize(obj);
  print('_id: '+obj._id+' || Size: '+size+'B -> '+Math.round(size/(1000))+'KB -> '+Math.round(size/(1000*1000))+'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:

db.users.find().forEach(function(obj)
{
  var size = Object.bsonsize(obj);
  var stats =
  {
    '_id': obj._id, 
    'bytes': size, 
    'KB': Math.round(size/(1000)), 
    'MB': Math.round(size/(1000*1000))
  };
  print(stats);
});

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


edit : thanks to @zAlbee for your suggest completion.