Mongo = get size of single document

半城伤御伤魂 提交于 2019-11-27 06:31:52
user1949763

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:

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

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.

Liberateur

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

db.users.find().forEach(function(obj)
{
  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:

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

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

source : https://stackoverflow.com/a/16957505/3933634

edit : thanks to @zAlbee for your suggest completion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!