MongoDB query to match each element in a documents array to a condition?

To match each element in a document's array to a condition in MongoDB, use the $where operator with JavaScript's every() method. This approach allows you to verify that all array elements satisfy a specific condition.

Syntax

db.collection.find({
    $where: "return this.arrayField.every(function(element) { 
        return (condition); 
    })"
});

Sample Data

db.arrayConditionDemo.insertMany([
    {"Name": "John", "Marks": [40, 43, 45]},
    {"Name": "Mike", "Marks": [45]},
    {"Name": "Chris", "Marks": [43, 45, 59, 69, 78, 89]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cbdbd06de8cc557214c0e1a"),
        ObjectId("5cbdbd17de8cc557214c0e1b"),
        ObjectId("5cbdbd3cde8cc557214c0e1c")
    ]
}

Display All Documents

db.arrayConditionDemo.find().pretty();
{
    "_id": ObjectId("5cbdbd06de8cc557214c0e1a"),
    "Name": "John",
    "Marks": [40, 43, 45]
}
{
    "_id": ObjectId("5cbdbd17de8cc557214c0e1b"),
    "Name": "Mike",
    "Marks": [45]
}
{
    "_id": ObjectId("5cbdbd3cde8cc557214c0e1c"),
    "Name": "Chris",
    "Marks": [43, 45, 59, 69, 78, 89]
}

Example: Match All Elements in Range

Find documents where all marks are between 40 and 100 ?

db.arrayConditionDemo.find({
    $where: "return this.Marks.every(function(m) { 
        return (m >= 40 && m <= 100); 
    })"
});
{"_id": ObjectId("5cbdbd06de8cc557214c0e1a"), "Name": "John", "Marks": [40, 43, 45]}
{"_id": ObjectId("5cbdbd17de8cc557214c0e1b"), "Name": "Mike", "Marks": [45]}
{"_id": ObjectId("5cbdbd3cde8cc557214c0e1c"), "Name": "Chris", "Marks": [43, 45, 59, 69, 78, 89]}

Key Points

  • $where executes JavaScript expressions on the server side.
  • every() returns true only if all array elements satisfy the condition.
  • Use this.fieldName to reference document fields in the JavaScript function.
  • Performance note: $where is slower than regular MongoDB operators for large collections.

Conclusion

The $where operator with JavaScript's every() method provides a flexible way to validate that all elements in an array meet specific conditions. While powerful, consider performance implications for large datasets.

Updated on: 2026-03-15T00:51:56+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements