Find values group by another field in MongoDB?

To group by another field in MongoDB, use $group along with $project. This approach allows you to aggregate documents based on a specific field while collecting values from other fields.

Syntax

db.collection.aggregate([
    {$match: {field: "value"}},
    {$group: {"_id": "$groupByField", "collectedField": {$addToSet: "$fieldToCollect"}}},
    {$project: {"_id": 0, "groupByField": "$_id", "collectedField": 1}}
]);

Sample Data

db.demo374.insertMany([
    {
        "Name": "Chris",
        "HobbyDetails": ["Reading Book", "Playing Football"],
        "CountryName": "US"
    },
    {
        "Name": "Chris",
        "HobbyDetails": ["Browsing Internet", "Playing Football"],
        "CountryName": "US"
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e5a04402ae06a1609a00b04"),
        ObjectId("5e5a04402ae06a1609a00b05")
    ]
}

Display Documents

db.demo374.find();
{ "_id": ObjectId("5e5a04402ae06a1609a00b04"), "Name": "Chris", "HobbyDetails": [ "Reading Book", "Playing Football" ], "CountryName": "US" }
{ "_id": ObjectId("5e5a04402ae06a1609a00b05"), "Name": "Chris", "HobbyDetails": [ "Browsing Internet", "Playing Football" ], "CountryName": "US" }

Example: Group Hobbies by Name

db.demo374.aggregate([
    {$match: {"CountryName": "US"}},
    {$group: {"_id": "$Name", "HobbyDetails": {$addToSet: "$HobbyDetails"}}},
    {$project: {
        "_id": 0, 
        "Name": "$_id", 
        "HobbyDetails": {
            $reduce: {
                input: "$HobbyDetails", 
                initialValue: [], 
                in: {$concatArrays: ["$$value", "$$this"]}
            }
        }
    }}
]);
{
    "Name": "Chris",
    "HobbyDetails": [
        "Browsing Internet",
        "Playing Football",
        "Reading Book",
        "Playing Football"
    ]
}

How It Works

  • $match filters documents by CountryName
  • $group groups by Name and collects HobbyDetails arrays using $addToSet
  • $project reshapes output and flattens nested arrays using $reduce

Conclusion

Use $group with $addToSet to collect values by another field. Combine with $reduce and $concatArrays to flatten nested arrays when needed.

Updated on: 2026-03-15T02:43:05+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements