MongoDB query to count records on the basis of matching criteria

To count records on the basis of matching criteria in MongoDB, use the countDocuments() method with a query filter. This method returns the number of documents that match the specified criteria.

Syntax

db.collection.countDocuments({field1: value1, field2: value2})

Sample Data

Let us create a collection with documents ?

db.demo205.insertMany([
    {
        "id": "101",
        "Name": "",
        "Age": "",
        "isActive": false
    },
    {
        "id": "102", 
        "Name": "Chris",
        "Age": "25",
        "isActive": true
    },
    {
        "id": "103",
        "Name": "",
        "Age": "",
        "isActive": false
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3d8a3003d395bdc21346eb"),
        ObjectId("5e3d8a3003d395bdc21346ec"), 
        ObjectId("5e3d8a3003d395bdc21346ed")
    ]
}

Display all documents from the collection ?

db.demo205.find();
{ "_id": ObjectId("5e3d8a3003d395bdc21346eb"), "id": "101", "Name": "", "Age": "", "isActive": false }
{ "_id": ObjectId("5e3d8a3003d395bdc21346ec"), "id": "102", "Name": "Chris", "Age": "25", "isActive": true }
{ "_id": ObjectId("5e3d8a3003d395bdc21346ed"), "id": "103", "Name": "", "Age": "", "isActive": false }

Example

Count documents where Name and Age are empty strings and isActive is false ?

db.demo205.countDocuments({
    Name: "",
    Age: "",
    "isActive": false
});
2

Key Points

  • Use countDocuments() instead of deprecated count() method for better accuracy.
  • Multiple criteria are combined with AND logic by default.
  • Empty query {} counts all documents in the collection.

Conclusion

The countDocuments() method efficiently counts documents matching specific criteria. It provides accurate results and should be used instead of the deprecated count() method.

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

688 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements