 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
How would I 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
 