Find largest document size in MongoDB

前端 未结 7 558
耶瑟儿~
耶瑟儿~ 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:56

    Well.. this is an old question.. but - I thought to share my cent about it

    My approach - use Mongo mapReduce function

    First - let's get the size for each document

    db.myColection.mapReduce
    (
       function() { emit(this._id, Object.bsonsize(this)) }, // map the result to be an id / size pair for each document
       function(key, val) { return val }, // val = document size value (single value for each document)
       { 
           query: {}, // query all documents
           out: { inline: 1 } // just return result (don't create a new collection for it)
       } 
    )
    

    This will return all documents sizes although it worth mentioning that saving it as a collection is a better approach (the result is an array of results inside the result field)

    Second - let's get the max size of document by manipulating this query

    db.metadata.mapReduce
    (
        function() { emit(0, Object.bsonsize(this))}, // mapping a fake id (0) and use the document size as value
        function(key, vals) { return Math.max.apply(Math, vals) }, // use Math.max function to get max value from vals (each val = document size)
        { query: {}, out: { inline: 1 } } // same as first example
    )
    

    Which will provide you a single result with value equals to the max document size

    In short:

    you may want to use the first example and save its output as a collection (change out option to the name of collection you want) and applying further aggregations on it (max size, min size, etc.)

    -OR-

    you may want to use a single query (the second option) for getting a single stat (min, max, avg, etc.)

提交回复
热议问题