
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 to Fetch Documents with Specific Field Value
For this, use aggregate(). Let’s say we have to fetch documents with a field “Age” with value “21”.
Let us now create a collection with documents −
> db.demo685.insertOne( ... { ... "details": ... [ ... { ... Name:"Chris", ... Age:21 ... }, ... { ... Name:"David", ... Age:23 ... }, ... { ... Name:"Bob", ... Age:21 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea54f6fa7e81adc6a0b395b") }
Display all documents from a collection with the help of find() method −
> db.demo685.find();
This will produce the following output −
{ "_id" : ObjectId("5ea54f6fa7e81adc6a0b395b"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 21 } ] }
Following is the query for MongoDB aggregation −
> db.demo685.aggregate([ { $unwind: "$details" }, { $match: { "details.Age": 21 } }, { $project: {_id: 0}} ]).pretty();
This will produce the following output −
{ "details" : { "Name" : "Chris", "Age" : 21 } } { "details" : { "Name" : "Bob", "Age" : 21 } }
Advertisements