- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
MongoDB filter multiple sub-documents?
To filter multiple sub-documents in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo200.insertOne( ... { ... "Id":"101", ... "details1":[ ... { ... "isActive":true, ... "SubjectName":"MySQL" ... },{ ... "isActive":false, ... "SubjectName":"Java" ... } ... ], ... "details2":[ ... { ... "isActive":false, ... "Name":"David" ... },{ ... "isActive":true, ... "Name":"Mike" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3c374f03d395bdc21346e4") }
Display all documents from a collection with the help of find() method −
> db.demo200.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c374f03d395bdc21346e4"), "Id" : "101", "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" }, { "isActive" : false, "SubjectName" : "Java" } ], "details2" : [ { "isActive" : false, "Name" : "David" }, { "isActive" : true, "Name" : "Mike" } ] }
Following is the query to filter multiple sub-documents −
> var out= [ ... { ... "$match": { ... "Id": "101", ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { "$unwind": "$details1" }, ... { "$unwind": "$details2" }, ... { ... "$match": { ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { ... "$group": { ... "_id": { ... "_id": "$_id", ... "Id": "$Id" ... }, ... "details2": { "$addToSet" : "$details2" }, ... "details1": { "$addToSet" : "$details1" } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Id": "$_id.Id", ... "details2": 1, ... "details1": 1 ... } ... } ...] > > db.demo200.aggregate(out)
This will produce the following output −
{ "details2" : [ { "isActive" : true, "Name" : "Mike" } ], "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" } ], "Id" : "101" }
Advertisements