Find the MongoDB collection size for name "Chris

To find the MongoDB collection size for documents with specific field values, use Object.bsonsize() within a forEach() loop to calculate the total BSON size of matching documents.

Syntax

var totalSize = 0;
db.collection.find({fieldName: "value"}).forEach(function(doc) {
    totalSize += Object.bsonsize(doc);
});
print(totalSize);

Sample Data

db.demo250.insertMany([
    {"Name": "Chris"},
    {"Name": "Bob"},
    {"Name": "David"},
    {"Name": "Chris"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e46bd501627c0c63e7dba70"),
        ObjectId("5e46bd531627c0c63e7dba71"),
        ObjectId("5e46bd561627c0c63e7dba72"),
        ObjectId("5e46bd5b1627c0c63e7dba73")
    ]
}

Verify Collection Data

db.demo250.find();
{ "_id": ObjectId("5e46bd501627c0c63e7dba70"), "Name": "Chris" }
{ "_id": ObjectId("5e46bd531627c0c63e7dba71"), "Name": "Bob" }
{ "_id": ObjectId("5e46bd561627c0c63e7dba72"), "Name": "David" }
{ "_id": ObjectId("5e46bd5b1627c0c63e7dba73"), "Name": "Chris" }

Calculate Size for Name "Chris"

var totalSize = 0;
db.demo250.find({Name: "Chris"}).forEach(function(doc) {
    totalSize += Object.bsonsize(doc);
});
print(totalSize);
76

Key Points

  • Object.bsonsize() returns the BSON size of each document in bytes.
  • The forEach() method iterates through all matching documents.
  • Size includes the document structure, field names, and ObjectId values.

Conclusion

Use Object.bsonsize() with forEach() to calculate the total storage size of documents matching specific criteria. This method provides accurate BSON byte measurements for filtered collections.

Updated on: 2026-03-15T02:03:43+05:30

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements