
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
Filter Out Sub-Documents in MongoDB
To filter out sub documents, use MongoDB aggregate and in that, use $unwind. Let us create a collection with documents −
> db.demo662.insertOne( ... { ... "details":[ ... { ... Name:"Chris", ... Marks:35 ... }, ... { ... Name:"Bob", ... Marks:45 ... }, ... { ... Name:"David", ... Marks:30 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea1b2be24113ea5458c7d04") }
Display all documents from a collection with the help of find() method −
> db.demo662.find();
This will produce the following output −
{ "_id" : ObjectId("5ea1b2be24113ea5458c7d04"), "details" : [ { "Name" : "Chris", "Marks" : 35 }, { "Name" : "Bob", "Marks" : 45 }, { "Name" : "David", "Marks" : 30 } ] }
Following is the query to filter out sub documents −
> db.demo662.aggregate({$unwind:"$details"},{$match:{"details.Marks":{$gt:40}}})
This will produce the following output −
{ "_id" : ObjectId("5ea1b2be24113ea5458c7d04"), "details" : { "Name" : "Bob", "Marks" : 45 } }
Advertisements