Find largest document size in MongoDB

前端 未结 7 537
耶瑟儿~
耶瑟儿~ 2020-12-01 01:33

Is it possible to find the largest document size in MongoDB?

db.collection.stats() shows average size, which is not really representative because in my

7条回答
  •  [愿得一人]
    2020-12-01 01:57

    Starting Mongo 4.4, the new aggregation operator $bsonSize returns the size in bytes of a given document when encoded as BSON.

    Thus, in order to find the bson size of the document whose size is the biggest:

    // { "_id" : ObjectId("5e6abb2893c609b43d95a985"), "a" : 1, "b" : "hello" }
    // { "_id" : ObjectId("5e6abb2893c609b43d95a986"), "c" : 1000, "a" : "world" }
    // { "_id" : ObjectId("5e6abb2893c609b43d95a987"), "d" : 2 }
    db.collection.aggregate([
      { $group: {
        _id: null,
        max: { $max: { $bsonSize: "$$ROOT" } }
      }}
    ])
    // { "_id" : null, "max" : 46 }
    

    This:

    • $groups all items together
    • $projects the $max of documents' $bsonSize
    • $$ROOT represents the current document for which we get the bsonsize

提交回复
热议问题