MongoDB $unwind to get the count

The $unwind operator in MongoDB deconstructs an array field from input documents to output a separate document for each array element. Use $unwind with $group and $count in an aggregation pipeline to get counts of array elements.

Syntax

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

Sample Data

db.demo478.insertMany([
    {
        "Details": {
            "_id": 1,
            "Information": [
                { "Name": "Chris", "Age": 21 },
                { "Name": "David", "Age": 23 },
                { "Name": null, "Age": 22 },
                { "Name": null, "Age": 24 }
            ]
        }
    },
    {
        "Details": {
            "_id": 2,
            "Information": [
                { "Name": "Bob", "Age": 21 },
                { "Name": null, "Age": 20 }
            ]
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Example: Count Non-Null Names by Age

Let's count how many people with non-null names exist for each age group ?

db.demo478.aggregate([
    { "$unwind": "$Details.Information" },
    {
        "$group": {
            "_id": "$Details.Information.Age",
            "count": {
                "$sum": {
                    "$cond": [
                        { "$gt": ["$Details.Information.Name", null] },
                        1, 0
                    ]
                }
            }
        }
    },
    { "$sort": { "count": -1 } }
]);
{ "_id": 21, "count": 2 }
{ "_id": 23, "count": 1 }
{ "_id": 24, "count": 0 }
{ "_id": 20, "count": 0 }
{ "_id": 22, "count": 0 }

How It Works

  • $unwind creates separate documents for each array element
  • $group groups by age and counts non-null names using $cond
  • $sort orders results by count in descending order
  • $gt: [field, null] checks if the name field is not null

Conclusion

Use $unwind with $group to count array elements based on conditions. The $cond operator allows conditional counting, making it powerful for filtering specific array values during aggregation.

Updated on: 2026-03-15T03:06:48+05:30

610 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements