Implement MongoDB Aggregate - unwind, group and project?

The MongoDB aggregation framework allows you to process data through a pipeline of stages. Three powerful operators - $unwind, $group, and $project - can be combined to deconstruct arrays, group documents, and shape the output.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $group: { _id: "$groupField", result: { $operator: "$field" } } },
    { $project: { field1: 1, field2: 1, _id: 0 } }
]);

Sample Data

db.demo238.insertMany([
    {
        "EmailId": "John@gmail.com",
        "details": [
            {
                "Name": "Bob",
                "isActive": true
            }
        ]
    },
    {
        "EmailId": "Chris@gmail.com",
        "details": [
            {
                "Name": "David"
            }
        ]
    },
    {
        "EmailId": "Mike@gmail.com",
        "details": [
            {
                "Name": "Carol",
                "isActive": true
            }
        ]
    }
]);

Display Documents

db.demo238.find().pretty();
{
    "_id": ObjectId("5e4418e3f4cebbeaebec5152"),
    "EmailId": "John@gmail.com",
    "details": [
        {
            "Name": "Bob",
            "isActive": true
        }
    ]
}
{
    "_id": ObjectId("5e4418e3f4cebbeaebec5153"),
    "EmailId": "Chris@gmail.com",
    "details": [
        {
            "Name": "David"
        }
    ]
}
{
    "_id": ObjectId("5e4418e4f4cebbeaebec5154"),
    "EmailId": "Mike@gmail.com",
    "details": [
        {
            "Name": "Carol",
            "isActive": true
        }
    ]
}

Example: Unwind, Group and Project

Find all active users and group them by name ?

db.demo238.aggregate([
    { "$match": { "details.isActive": true } },
    { "$unwind": "$details" },
    { "$match": { "details.isActive": true } },
    { "$group": {
        "_id": "$details.Name",
        "active": { "$first": "$_id" }
    }}
]);
{ "_id": "Carol", "active": ObjectId("5e4418e4f4cebbeaebec5154") }
{ "_id": "Bob", "active": ObjectId("5e4418e3f4cebbeaebec5152") }

How It Works

  • $match: Filters documents that have active users in the details array
  • $unwind: Deconstructs the details array, creating one document per array element
  • $match: Filters the unwound documents to keep only active users
  • $group: Groups by user name and captures the original document ID

Conclusion

The combination of $unwind, $group, and $project provides a powerful way to process array data in MongoDB. Use $unwind to flatten arrays, $group to aggregate data, and $project to shape the final output.

Updated on: 2026-03-15T02:01:47+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements