Find documents where all elements of an array have a specific value in MongoDB?

To find documents where all elements of an array have a specific value in MongoDB, use the $not operator with $elemMatch to exclude documents that contain any element NOT matching the desired value.

Syntax

db.collection.find({
    "arrayField": {
        $not: {
            $elemMatch: {
                "field": { $ne: "specificValue" }
            }
        }
    }
});

Sample Data

db.findDocumentsDemo.insertMany([
    {
        _id: 101,
        "ProductDetails": [
            { "ProductValue": 100 },
            { "ProductValue": 120 }
        ]
    },
    {
        _id: 102,
        "ProductDetails": [
            { "ProductValue": 120 },
            { "ProductValue": 120 },
            { "ProductValue": 120 }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": { "0": 101, "1": 102 }
}

Example: Find All ProductValue = 120

Find documents where all array elements have ProductValue of 120 ?

db.findDocumentsDemo.find({
    "ProductDetails": {
        $not: {
            $elemMatch: {
                "ProductValue": { $ne: 120 }
            }
        }
    }
});
{
    "_id": 102,
    "ProductDetails": [
        { "ProductValue": 120 },
        { "ProductValue": 120 },
        { "ProductValue": 120 }
    ]
}

How It Works

  • $elemMatch finds arrays containing at least one element NOT equal to 120
  • $not inverts this logic to exclude such documents
  • Result: only documents where all elements equal 120 remain

Conclusion

Use $not with $elemMatch and $ne to find documents where all array elements match a specific value. This approach excludes documents containing any non-matching elements.

Updated on: 2026-03-15T01:33:45+05:30

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements