- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB aggregation and projection?
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" } ] }
Advertisements