GROUP BY array of document to get the count of repeated Age values

To GROUP BY array of document to get count of repeated Age values, use the aggregation pipeline with $unwind to flatten the array and $group to count occurrences by Age.

Syntax

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

Sample Data

db.demo559.insertOne({
    details: [
        { Name: "Chris", Age: 21 },
        { Name: "Bob", Age: 22 },
        { Name: "Carol", Age: 21 },
        { Name: "Sam", Age: 21 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e8f38d954b4472ed3e8e866")
}

Verify Sample Data

db.demo559.find().pretty();
{
    "_id": ObjectId("5e8f38d954b4472ed3e8e866"),
    "details": [
        { "Name": "Chris", "Age": 21 },
        { "Name": "Bob", "Age": 22 },
        { "Name": "Carol", "Age": 21 },
        { "Name": "Sam", "Age": 21 }
    ]
}

Group by Age and Count Occurrences

db.demo559.aggregate([
    { $unwind: "$details" },
    { $group: {
        _id: "$details.Age",
        Count: { $sum: 1 }
    }},
    { $sort: { _id: 1 } }
]);
{ "_id": 21, "Count": 3 }
{ "_id": 22, "Count": 1 }

How It Works

  • $unwind − Flattens the details array, creating separate documents for each array element
  • $group − Groups documents by Age field and counts occurrences using $sum: 1
  • $sort − Sorts results by Age in ascending order

Conclusion

Use $unwind to deconstruct arrays, then $group with $sum: 1 to count repeated values. This pattern effectively transforms nested array data into grouped aggregation results.

Updated on: 2026-03-15T03:34:29+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements