- 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 query to filter object where all elements from nested array match the condition
For this, use aggregate(). Let us first create a collection with documents −
> db.demo418.insertOne( ... { ... "details":[ ... { ... "CountryName":"US", ... "Marks":45 ... }, ... { ... "CountryName":"US", ... "Marks":56 ... }, ... ... ], ... "Name":"John" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e724324b912067e57771ae6") } > db.demo418.insertOne( ... { ... "details":[ ... { ... "CountryName":"US", ... "Marks":78 ... }, ... { ... "CountryName":"UK", ... "Marks":97 ... }, ... ... ], ... "Name":"Mike" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e724325b912067e57771ae7") }
Display all documents from a collection with the help of find() method −
> db.demo418.find();
This will produce the following output −
{ "_id" : ObjectId("5e724324b912067e57771ae6"), "details" : [ { "CountryName" : "US", "Marks" : 45 }, { "CountryName" : "US", "Marks" : 56 } ], "Name" : "John" } { "_id" : ObjectId("5e724325b912067e57771ae7"), "details" : [ { "CountryName" : "US", "Marks" : 78 }, { "CountryName" : "UK", "Marks" : 97 } ], "Name" : "Mike" }
Following is the query to filter object where all elements from nested array match the condition −
> db.demo418.aggregate([ ... {$unwind:"$details"}, ... { $group: { ... _id: '$_id', ... details : { $first: '$details' }, ... alldetails: { $sum: 1 }, ... alldetailsmatch: { $sum: { $cond: [ { $eq: [ '$details.CountryName', "US" ] }, 1, 0 ] } }, ... Name: { $first: '$Name' } ... }}, ... { $project: { ... _id: 1, ... Name: 1, ... details: 1, ... arrayValue: { $cond: [ { $eq: [ '$alldetails', '$alldetailsmatch' ] }, 1, 0 ] } ... }}, ... { $match: { 'arrayValue' : 1 } } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e724324b912067e57771ae6"), "details" : { "CountryName" : "US", "Marks" : 45 }, "Name" : "John", "arrayValue" : 1 }
Advertisements