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 }

Updated on: 03-Apr-2020

617 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements