How to group nested fields in MongoDB aggregation with count value in array?

To group nested fields in MongoDB aggregation with count values from arrays, use the $objectToArray operator to convert nested objects into key-value pairs, then use $unwind and $group to aggregate the count values.

Syntax

db.collection.aggregate([
    { $project: { fieldName: { $objectToArray: "$nestedObject" } } },
    { $unwind: "$fieldName" },
    { $group: { _id: "$fieldName.k", count: { $sum: "$fieldName.v.countField" } } }
])

Sample Data

db.demo99.insertMany([
    {
        "Details": {
            "X": {
                "Values": [10, 30, 50],
                "Number": 3
            },
            "Y": {
                "Values": [1000, 180],
                "Number": 2
            }
        }
    },
    {
        "Details": {
            "X": {
                "Values": [100, 300, 500, 6000],
                "Number": 4
            },
            "Y": {
                "Values": [10, 20, 60],
                "Number": 3
            }
        }
    }
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display Sample Data

db.demo99.find()
{ "_id" : ObjectId("5e2d91eab8903cdd865577b9"), "Details" : { "X" : { "Values" : [ 10, 30, 50 ], "Number" : 3 }, "Y" : { "Values" : [ 1000, 180 ], "Number" : 2 } } }
{ "_id" : ObjectId("5e2d927bb8903cdd865577ba"), "Details" : { "X" : { "Values" : [ 100, 300, 500, 6000 ], "Number" : 4 }, "Y" : { "Values" : [ 10, 20, 60 ], "Number" : 3 } } }

Group Nested Fields with Count

db.demo99.aggregate([
    { $project: { Count: { $objectToArray: "$Details" } } },
    { $unwind: "$Count" },
    { $group: { _id: "$Count.k", count: { $sum: "$Count.v.Number" } } }
])
{ "_id" : "Y", "count" : 5 }
{ "_id" : "X", "count" : 7 }

How It Works

  • $objectToArray converts the nested "Details" object into an array of key-value pairs
  • $unwind creates separate documents for each key-value pair
  • $group groups by the key ("X" or "Y") and sums the "Number" values

Conclusion

Use $objectToArray, $unwind, and $group together to aggregate count values from nested object fields. This approach effectively transforms nested objects into groupable data structures for aggregation operations.

Updated on: 2026-03-15T01:54:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements