How to get the size of single document in Mongodb?

前端 未结 5 1524
情歌与酒
情歌与酒 2020-11-28 03:34

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 collect

相关标签:
5条回答
  • 2020-11-28 03:54

    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.

    0 讨论(0)
  • 2020-11-28 03:54

    Object.bsonsize(db.test.findOne({type:"auto"})) It gives in bytes.

    0 讨论(0)
  • 2020-11-28 04:04

    With mongodb 4.4 (upcoming), You can use bsonSize operator to get the document size.

    db.test.aggregate([
      {
        "$project": {
          "name": 1,
          "object_size": { "$bsonSize": "$$ROOT" }
        }
      }
    ])
    
    0 讨论(0)
  • 2020-11-28 04:06

    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.

    0 讨论(0)
  • 2020-11-28 04:11

    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.

    0 讨论(0)
提交回复
热议问题