Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to filter object where all elements from nested array match the condition
To filter objects where all elements from a nested array match a specific condition in MongoDB, use aggregation pipeline with $unwind, $group, and conditional counting to compare total elements against matching elements.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{
$group: {
_id: "$_id",
totalElements: { $sum: 1 },
matchingElements: { $sum: { $cond: [{ $eq: ["$arrayField.field", "value"] }, 1, 0] } },
otherFields: { $first: "$otherField" }
}
},
{ $match: { $expr: { $eq: ["$totalElements", "$matchingElements"] } } }
]);
Sample Data
db.demo418.insertMany([
{
"details": [
{ "CountryName": "US", "Marks": 45 },
{ "CountryName": "US", "Marks": 56 }
],
"Name": "John"
},
{
"details": [
{ "CountryName": "US", "Marks": 78 },
{ "CountryName": "UK", "Marks": 97 }
],
"Name": "Mike"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e724324b912067e57771ae6"),
ObjectId("5e724325b912067e57771ae7")
]
}
Example: Filter Documents Where All Countries are "US"
db.demo418.aggregate([
{ $unwind: "$details" },
{
$group: {
_id: "$_id",
Name: { $first: "$Name" },
alldetails: { $sum: 1 },
alldetailsmatch: { $sum: { $cond: [{ $eq: ["$details.CountryName", "US"] }, 1, 0] } }
}
},
{
$project: {
_id: 1,
Name: 1,
arrayValue: { $cond: [{ $eq: ["$alldetails", "$alldetailsmatch"] }, 1, 0] }
}
},
{ $match: { "arrayValue": 1 } }
]);
{
"_id": ObjectId("5e724324b912067e57771ae6"),
"Name": "John",
"arrayValue": 1
}
How It Works
-
$unwindbreaks down the array into separate documents for each element -
$groupcounts total elements and matching elements using conditional logic -
$projectcompares counts to determine if all elements match the condition -
$matchfilters documents where all elements satisfy the condition
Conclusion
Use aggregation pipeline with conditional counting to filter documents where all nested array elements match a specific condition. This approach compares total element count against matching element count to ensure complete array compliance.
Advertisements
