How can I count the documents in an array based on the value of a specific field?

To count documents in an array based on the value of a specific field, use the $unwind operator to flatten the array, followed by $match to filter, and $group to count the matching elements.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $match: { "arrayField.fieldName": "targetValue" } },
    { $group: { 
        _id: null,
        count: { $sum: 1 }
    }}
]);

Sample Data

db.demo726.insertOne({
    "id": 101,
    "details": [
        { "Name": "Chris" },
        { "Name": "Chris" },
        { "Name": "Bob" }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5eab318643417811278f5894")
}

Example: Count Array Elements by Field Value

Display all documents from the collection ?

db.demo726.find();
{
    "_id": ObjectId("5eab318643417811278f5894"),
    "id": 101,
    "details": [
        { "Name": "Chris" },
        { "Name": "Chris" },
        { "Name": "Bob" }
    ]
}

Count how many array elements have Name = "Chris" ?

db.demo726.aggregate([
    { $unwind: "$details" },
    { $match: { "details.Name": "Chris" } },
    { $group: {
        _id: null,
        Total_Value: { $sum: 1 }
    }}
]);
{ "_id": null, "Total_Value": 2 }

How It Works

  • $unwind creates separate documents for each array element
  • $match filters documents where the field matches the target value
  • $group counts the remaining documents with $sum: 1

Conclusion

Use the aggregation pipeline with $unwind, $match, and $group to count array elements based on field values. This approach efficiently flattens arrays and counts matching elements.

Updated on: 2026-03-15T03:51:41+05:30

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements