- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Implement $match and $project in MongoDB aggregate
The $match filters the documents to pass only the documents that match the specified condition to the next pipeline stage.
The $project passes along the documents with the requested fields to the next stage in the pipeline.
Let us see an example and create a collection with documents −
> db.demo545.insert({Name:"Chris",details:{SubjectScore1:56,SubjectScore2:56}}) WriteResult({ "nInserted" : 1 }) > db.demo545.insert({Name:"David",details:{SubjectScore1:78,SubjectScore2:78}}) WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo545.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e246e9e5f92834d7f05d5"), "Name" : "Chris", "details" : { "SubjectScore1" : 56, "SubjectScore2" : 56 } } { "_id" : ObjectId("5e8e24709e5f92834d7f05d6"), "Name" : "David", "details" : { "SubjectScore1" : 78, "SubjectScore2" : 78 } }
Following is the query to implement $match and $project −
>db.demo545.aggregate([{$match:{}},{$project:{"_id":0,"details.SubjectScore1":1,out:"$details .SubjectScore2"}},{$group:{_id:"$out"}}])
This will produce the following output −
{ "_id" : 78 } { "_id" : 56 }
- Related Articles
- Implement MongoDB Aggregate - unwind, group and project?
- MongoDB query to implement aggregate function
- Implement array match in MongoDB?
- Project field in MongoDB
- Get substring in MongoDB aggregate
- Using $redact in MongoDB aggregate?
- Need to aggregate by hour and $avg in MongoDB
- MongoDB aggregate query to sort
- MongoDB Aggregate group multiple result?
- Sort array in MongoDB query and project all fields?
- How to aggregate array documents in MongoDB?
- How to update after aggregate in MongoDB?
- Use MongoDB Aggregate and select only top record (descending)
- Split a string during MongoDB aggregate
- MongoDB query to aggregate nested array

Advertisements