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 where all array items are greater than a specified condition?
To query where all array elements are greater than a specified condition in MongoDB, use the $not operator combined with $elemMatch to exclude documents where any element fails the condition.
Syntax
db.collection.find({
"arrayField": { $not: { $elemMatch: { $lte: 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")
]
}
Display All Documents
db.arrayElementsNotGreaterThanDemo.find().pretty();
{
"_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]
}
Query: All Array Elements Greater Than 45
db.arrayElementsNotGreaterThanDemo.find({
"Scores": { $not: { $elemMatch: { $lte: 45 } } }
});
{
"_id": ObjectId("5cd9ea3cb50a6c6dd317adb6"),
"Scores": [46, 66, 77, 88]
}
How It Works
The $not operator excludes documents where $elemMatch finds any element less than or equal to 45. Only documents where all elements are greater than 45 remain.
Conclusion
Use $not with $elemMatch to find documents where all array elements satisfy a condition. This approach filters out documents containing any element that fails the specified criteria.
Advertisements
