Multilevel $group using MongoDB

To implement multilevel $group in MongoDB, use the aggregation pipeline with multiple $group stages to group data at different levels and create nested structures.

Syntax

db.collection.aggregate([
    { $group: { _id: { field1: "$field1", field2: "$field2" }, count: { $sum: 1 } } },
    { $group: { _id: "$_id.field1", nestedData: { $push: { k: "$_id.field2", v: "$count" } } } },
    { $addFields: { nestedData: { $arrayToObject: "$nestedData" } } }
]);

Sample Data

db.demo76.insertMany([
    { Name: "Chris", Age: 21, CountryName: "US" },
    { Name: "Chris", Age: 21, CountryName: "US" },
    { Name: "Chris", Age: 23, CountryName: "UK" },
    { Name: "Chris", Age: 23, CountryName: "UK" },
    { Name: "Chris", Age: 21, CountryName: "AUS" },
    { Name: "Chris", Age: 21, CountryName: "AUS" },
    { Name: "Chris", Age: 23, CountryName: "AUS" },
    { Name: "Chris", Age: 21, CountryName: "UK" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2bd3e571bf0181ecc42281"),
        ObjectId("5e2bd3e571bf0181ecc42282"),
        ...
    ]
}

Example: Multilevel Grouping

Group documents first by Age and CountryName, then create nested structure by Age ?

db.demo76.aggregate([
    { "$match": { "Name": "Chris" }},
    { "$group": {
        "_id": { "Age": "$Age", "CountryName": "$CountryName" },
        "count": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.Age",
        "CountryName": {
            "$push": {
                "k": "$_id.CountryName",
                "v": "$count"
            }
        }
    }},
    { "$addFields": {
        "CountryName": {
            "$arrayToObject": "$CountryName"
        }
    }}
]);
{ "_id": 23, "CountryName": { "AUS": 1, "UK": 2 } }
{ "_id": 21, "CountryName": { "UK": 1, "AUS": 2, "US": 2 } }

How It Works

  • First $group: Groups by both Age and CountryName, counting occurrences
  • Second $group: Groups by Age only, creating arrays of country-count pairs
  • $addFields: Converts arrays to objects using $arrayToObject

Conclusion

Multilevel $group operations allow complex data aggregation by grouping at multiple levels. Use $push to create arrays and $arrayToObject to convert them into nested object structures for better data organization.

Updated on: 2026-03-15T01:51:08+05:30

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements