For this, use $project along with aggregate(). The $project in aggregation passes along the documents with the requested fields to the next stage in the pipeline.
Let us create a collection with documents −
> db.demo762.insertOne({ ... "_id" : { ... "userId":101, ... "userName":"Chris" ... }, .. . "countryName" : "US", ... ... "details" : [ ... { ... "Name" : "Robert", ... "DueDate" : "2020-04-10" ... ... }, ... ... { ... "Name" : "Robert", ... "DueDate" : "2020-04-09" ... }, ... { ... "Name" : "Robert", ... "DueDate" : "2020-03-06" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : { "userId" : 101, "userName" : "Chris" } }
Display all documents from a collection with the help of find() method −
> db.demo762.find();
This will produce the following output −
{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-04-10" }, { "Name" : "Robert", "DueDate" : "2020-04-09" }, { "Name" : "Robert", "DueDate" : "2020-03-06" } ] }
Following is the query for MongoDB aggregation and projection −
> db.demo762.aggregate([ ... { "$match": { ... "_id": { "$eq": { userId:101,userName:"Chris" }} ... }}, ... { "$unwind": "$details" }, ... { "$sort": { "details.DueDate": 1 }}, ... { "$group": { ... "_id": "$_id", ... "details": { "$push": "$details" }, ... "countryName": { "$first": "$countryName" } ... }}, ... { "$project": { "details": { "$slice": ["$details", 2] } ,"countryName": 1 }} ... ]).pretty();
This will produce the following output −
{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-03-06" }, { "Name" : "Robert", "DueDate" : "2020-04-09" } ] }