Retrieving group by result with arrays in MongoDB?

To retrieve group by result with arrays in MongoDB, use aggregate() with $unwind and $group stages. The $addToSet operator adds values to an array unless the value is already present, preventing duplicates.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    {
        $group: {
            _id: "$fieldToGroupBy",
            resultArray: { $addToSet: "$fieldToCollect" }
        }
    }
])

Sample Data

db.demo498.insertMany([
    { id: 1, Name: ["Chris"] },
    { id: 2, Name: ["David"] },
    { id: 3, Name: ["Chris"] },
    { id: 4, Name: ["Bob"] },
    { id: 5, Name: ["David"] }
])
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("..."),
        "1": ObjectId("..."),
        "2": ObjectId("..."),
        "3": ObjectId("..."),
        "4": ObjectId("...")
    }
}

Display all documents from the collection ?

db.demo498.find()
{ "_id": ObjectId("5e86192b987b6e0e9d18f553"), "id": 1, "Name": ["Chris"] }
{ "_id": ObjectId("5e86192d987b6e0e9d18f554"), "id": 2, "Name": ["David"] }
{ "_id": ObjectId("5e861931987b6e0e9d18f555"), "id": 3, "Name": ["Chris"] }
{ "_id": ObjectId("5e861942987b6e0e9d18f556"), "id": 4, "Name": ["Bob"] }
{ "_id": ObjectId("5e861947987b6e0e9d18f557"), "id": 5, "Name": ["David"] }

Group by Names and Collect IDs

Retrieve group by result with arrays to collect all id values for each unique name ?

db.demo498.aggregate([
    {
        $unwind: "$Name"
    },
    {
        $group: {
            _id: "$Name",
            Id: {
                $addToSet: "$id"
            }
        }
    }
])
{ "_id": "David", "Id": [5, 2] }
{ "_id": "Bob", "Id": [4] }
{ "_id": "Chris", "Id": [3, 1] }

How It Works

  • $unwind − Deconstructs the Name array, creating separate documents for each array element
  • $group − Groups documents by the Name field value
  • $addToSet − Collects unique id values into an array for each group

Conclusion

Use $unwind to flatten arrays, then $group with $addToSet to create grouped results with collected values. This approach effectively groups documents by array elements and aggregates related data.

Updated on: 2026-03-15T03:18:33+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements