
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 sub documents by sub document in MongoDB?
For this, use aggregate() along with $unwind. Let us create a collection with documents −
> db.demo583.insert([ ... { ... "details1" : [ ... { ... "details2" : [ ... { ... "isMarried" : true, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Bob" ... } ... ] ... }, ... { ... "details2" : [ ... { ... "isMarried" : false, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
Display all documents from a collection with the help of find() method −
> db.demo583.find();
This will produce the following output −
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [ { "details2" : [ { "isMarried" : true, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Bob" } ] }, { "details2" : [ { "isMarried" : false, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Mike" } ] } ] }
Following is the query to filter sub documents by sub-document −
> var q= [ ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... }, ... { ... "$unwind": "$details1" ... }, ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... } ... ]; > db.demo583.aggregate(q).pretty();
This will produce the following output −
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : { "details2" : { "isMarried" : true, "Name" : "Chris" } } }
- Related Questions & Answers
- MongoDB filter multiple sub-documents?
- How would I filter out sub documents in MongoDB?
- Sum MongoDB Sub-documents field?
- How to add a sub-document to sub-document array in MongoDB?
- MongoDB query by sub-field?
- Find the MongoDB document from sub array?
- Working with MongoDB $sort for sub array document
- Finding highest value from sub-arrays in MongoDB documents?
- How to fire find query on sub-documents in MongoDB?
- How do I return a document with filtered sub-documents using Mongo?
- Pull an element in sub of sub-array in MongoDB?
- How to sum every field in a sub document of MongoDB?
- Updating sub-object in MongoDB?
- Get fields from multiple sub-documents that match a condition in MongoDB?
- How to add an extra field in a sub document in MongoDB?
Advertisements