MongoDB query where all array items are less than a specified condition?

To query MongoDB documents where all array items are less than a specified condition, use the $not operator combined with $gt. This approach ensures that no element in the array is greater than the specified value.

Syntax

db.collection.find({
    "arrayField": { $not: { $gt: value } }
});

Sample Data

db.arrayElementsNotGreaterThanDemo.insertMany([
    {"Scores": [89, 43, 32, 45]},
    {"Scores": [32, 33, 34, 40]},
    {"Scores": [45, 56, 66, 69]},
    {"Scores": [46, 66, 77, 88]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd9e9f9b50a6c6dd317adb3"),
        ObjectId("5cd9ea13b50a6c6dd317adb4"),
        ObjectId("5cd9ea25b50a6c6dd317adb5"),
        ObjectId("5cd9ea3cb50a6c6dd317adb6")
    ]
}

View Sample Data

db.arrayElementsNotGreaterThanDemo.find();
{
    "_id": ObjectId("5cd9e9f9b50a6c6dd317adb3"),
    "Scores": [89, 43, 32, 45]
}
{
    "_id": ObjectId("5cd9ea13b50a6c6dd317adb4"),
    "Scores": [32, 33, 34, 40]
}
{
    "_id": ObjectId("5cd9ea25b50a6c6dd317adb5"),
    "Scores": [45, 56, 66, 69]
}
{
    "_id": ObjectId("5cd9ea3cb50a6c6dd317adb6"),
    "Scores": [46, 66, 77, 88]
}

Example: Find Arrays Where All Elements ? 45

db.arrayElementsNotGreaterThanDemo.find({
    Scores: { $not: { $gt: 45 } }
});
{ "_id": ObjectId("5cd9ea13b50a6c6dd317adb4"), "Scores": [32, 33, 34, 40] }

How It Works

The query { $not: { $gt: 45 } } means "not greater than 45", which effectively finds documents where all array elements are less than or equal to 45. Only the second document qualifies because all its scores (32, 33, 34, 40) are ? 45.

Conclusion

Use $not with $gt to find documents where all array elements meet a "less than" condition. This approach leverages MongoDB's logical negation to achieve the desired filtering result.

Updated on: 2026-03-15T01:17:53+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements