Implement MongoDB Aggregate - unwind, group and project?


The $unwind in MongoDB deconstructs an array field from the input documents to output a document for each element.

$group is used to group input documents by the specified _id expression and for each distinct grouping, outputs a document.

$project is used to pass along the documents with the requested fields to the next stage in the pipeline.

Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method:

> db.demo238.find().pretty();

This will produce the following output −

{
   "_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
      }
   ]
}

Following is the query to implement MongoDB Aggregate - unwind, group and project −

> db.demo238.aggregate(
...   [
...      { "$match": { "details.isActive": true } },
...      { "$unwind": "$details" },
...      { "$match": { "details.isActive": true } },
...      { "$group": {
...         "_id": "$details.Name",
...         "active": { "$first": "$_id" }
...      }}
...   ],
...   function(err,result) {
...
...   }
...);

This will produce the following output −

{ "_id" : "Carol", "active" : ObjectId("5e4418e4f4cebbeaebec5154") }
{ "_id" : "Bob", "active" : ObjectId("5e4418e3f4cebbeaebec5152") }

Updated on: 30-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements