Get the size of a collection in MongoDB using conditions?

To get the size of a MongoDB collection using specific conditions, you can filter documents with a query and then calculate the total size of matching documents using Object.bsonSize() within a forEach() loop.

Syntax

var collectionSize = 0;
db.collection.find({condition}).forEach(function(document) {
    var size = Object.bsonSize(document);
    collectionSize = collectionSize + size;
});
print(collectionSize);

Sample Data

Let us create a collection with sample documents ?

db.mongoDBCollectionSizeDemo.insertMany([
    {"Name": "John", "Age": 23},
    {"Name": "Chris", "Age": 24},
    {"Name": "Robert", "Age": 26}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cf23e3db64a577be5a2bc16"),
        ObjectId("5cf23e45b64a577be5a2bc17"),
        ObjectId("5cf23e4db64a577be5a2bc18")
    ]
}

Display all documents from the collection ?

db.mongoDBCollectionSizeDemo.find();
{ "_id": ObjectId("5cf23e3db64a577be5a2bc16"), "Name": "John", "Age": 23 }
{ "_id": ObjectId("5cf23e45b64a577be5a2bc17"), "Name": "Chris", "Age": 24 }
{ "_id": ObjectId("5cf23e4db64a577be5a2bc18"), "Name": "Robert", "Age": 26 }

Example: Get Size with Condition

Calculate the total size of documents where Name equals "Robert" ?

var collectionsize = 0;
db.mongoDBCollectionSizeDemo.find({Name: 'Robert'}).forEach(function(d) {
    var s = Object.bsonSize(d);
    collectionsize = collectionsize + s;
});
print(collectionsize);
52

Key Points

  • Object.bsonSize() returns the BSON size of a document in bytes.
  • The forEach() method iterates through filtered documents to calculate cumulative size.
  • This approach works with any MongoDB query condition.

Conclusion

Use Object.bsonSize() with forEach() to calculate the total size of documents matching specific conditions. This method provides precise byte-level size calculations for filtered collections.

Updated on: 2026-03-15T01:30:05+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements