3

I would like to know if it is possible to sort a MongoDB collection by the document size measured in bytes/kb. I have been checking out db.collection.stats() however this only gives me information about the collection and not the document.

2 Answers 2

5

A possible solution is to add an extra "size" field in you documents, given that document size is not frequently changed.

To add size for each document:

db.collection.find().forEach(function(doc) {
    doc.size = Object.bsonsize(doc); 
    db.collection.save(doc);
});

To sort in descending order:

db.collection.find().sort({"size":-1});

Another solution is to load all documents in memory, sort and print out the results with any programming language (js, php, java...), which is not recommended if your collection is big.

0
5

From Mongo 4.4, operator $bsonSize returns the size in bytes of a given document.

To find biggest document

db.collection.aggregate([
  { $group: {
    _id: null,
    max: { $max: { $bsonSize: "$$ROOT" } }
  }}
])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.