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

  • $unwind breaks down the array into separate documents for each element
  • $group counts total elements and matching elements using conditional logic
  • $project compares counts to determine if all elements match the condition
  • $match filters 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.

Updated on: 2026-03-15T02:55:08+05:30

833 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements