Find largest document size in MongoDB

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

    Inspired by Elad Nana's package, but usable in a MongoDB console :

    function biggest(collection, limit=100, sort_delta=100) {
      var documents = [];
      cursor = collection.find().readPref("nearest");
      while (cursor.hasNext()) {
        var doc = cursor.next();
        var size = Object.bsonsize(doc);
        if (documents.length < limit || size > documents[limit-1].size) {
          documents.push({ id: doc._id.toString(), size: size });
        }
        if (documents.length > (limit + sort_delta) || !cursor.hasNext()) {
          documents.sort(function (first, second) {
            return second.size - first.size;
          });
          documents = documents.slice(0, limit);
        }
      }
      return documents;
    }; biggest(db.collection)
    
    • Uses cursor
    • Gives a list of the limit biggest documents, not just the biggest
    • Sort & cut output list to limit every sort_delta
    • Use nearest as read preference (you might also want to use rs.slaveOk() on the connection to be able to list collections if you're on a slave node)

提交回复
热议问题