Get the count of a specific value in MongoDB

To get the count of a specific value in MongoDB, use the aggregate() method with $unwind and $group stages to count occurrences of array elements or use $size with $filter for a more efficient approach.

Syntax

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

Sample Data

db.demo210.insertOne({
    details: [
        { ClientName: "Robert" },
        { ClientName: "John Doe" },
        { ClientName: "Robert" },
        { ClientName: "Robert" },
        { ClientName: "David Miller" }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e3d99ab03d395bdc21346f9")
}

Display Sample Data

db.demo210.find();
{
    "_id": ObjectId("5e3d99ab03d395bdc21346f9"),
    "details": [
        { "ClientName": "Robert" },
        { "ClientName": "John Doe" },
        { "ClientName": "Robert" },
        { "ClientName": "Robert" },
        { "ClientName": "David Miller" }
    ]
}

Method 1: Using $unwind and $group

Count how many times "Robert" appears in the details array ?

db.demo210.aggregate([
    { $match: { "details.ClientName": "Robert" } },
    { $unwind: "$details" },
    { $match: { "details.ClientName": "Robert" } },
    { $group: { _id: "$_id", count: { $sum: 1 } } }
]);
{ "_id": ObjectId("5e3d99ab03d395bdc21346f9"), "count": 3 }

Method 2: Using $filter and $size (Recommended)

A more efficient approach using $filter to count specific values ?

db.demo210.aggregate([
    {
        $project: {
            count: {
                $size: {
                    $filter: {
                        input: "$details",
                        cond: { $eq: ["$$this.ClientName", "Robert"] }
                    }
                }
            }
        }
    }
]);
{ "_id": ObjectId("5e3d99ab03d395bdc21346f9"), "count": 3 }

Key Points

  • $unwind deconstructs arrays into separate documents for counting.
  • $filter with $size is more efficient as it doesn't create intermediate documents.
  • Use double $match stages to filter before and after unwinding for better performance.

Conclusion

Both methods effectively count specific values in arrays. The $filter approach is more efficient for simple counting, while $unwind provides flexibility for complex aggregations on array elements.

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

460 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements