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" : "[email protected]", ... "details" : [ ... { ... "Name" : "Bob", ... "isActive" : true ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4418e3f4cebbeaebec5152") } > > db.demo238.insertOne( ... { ... ... "EmailId" : "[email protected]", ... "details" : [ ... { ... "Name" : "David" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4418e3f4cebbeaebec5153") } > > > db.demo238.insertOne( ... { ... ... "EmailId" : "[email protected]", ... "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" : "[email protected]", "details" : [ { "Name" : "Bob", "isActive" : true } ] } { "_id" : ObjectId("5e4418e3f4cebbeaebec5153"), "EmailId" : "[email protected]", "details" : [ { "Name" : "David" } ] } { "_id" : ObjectId("5e4418e4f4cebbeaebec5154"), "EmailId" : "[email protected]", "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") }