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
Find value in a MongoDB Array with multiple criteria?
To find values in a MongoDB array with multiple criteria, use the $elemMatch operator combined with comparison operators like $gt and $lt. This allows you to match documents where at least one array element satisfies all specified conditions.
Syntax
db.collectionName.find({
arrayFieldName: {
$elemMatch: {
$gt: lowerValue,
$lt: upperValue
}
}
});
Sample Data
Let's create a collection with student records containing marks arrays ?
db.findValueInArrayWithMultipleCriteriaDemo.insertMany([
{
"StudentName": "Larry",
"StudentMarks": [-150, 150]
},
{
"StudentName": "Mike",
"StudentMarks": [19]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c77daf6fc4e719b197a12f5"),
ObjectId("5c77db09fc4e719b197a12f6")
]
}
View Sample Data
db.findValueInArrayWithMultipleCriteriaDemo.find();
{
"_id": ObjectId("5c77daf6fc4e719b197a12f5"),
"StudentName": "Larry",
"StudentMarks": [-150, 150]
}
{
"_id": ObjectId("5c77db09fc4e719b197a12f6"),
"StudentName": "Mike",
"StudentMarks": [19]
}
Example: Find Students with Marks Between -20 and 20
Find students who have at least one mark greater than -20 and less than 20 ?
db.findValueInArrayWithMultipleCriteriaDemo.find({
StudentMarks: {
$elemMatch: {
$gt: -20,
$lt: 20
}
}
});
{
"_id": ObjectId("5c77db09fc4e719b197a12f6"),
"StudentName": "Mike",
"StudentMarks": [19]
}
Key Points
-
$elemMatchensures all conditions are satisfied by the same array element - Larry's document is excluded because neither -150 nor 150 falls within the -20 to 20 range
- Mike's document matches because 19 satisfies both conditions (> -20 AND
Conclusion
Use $elemMatch with multiple comparison operators to find documents where array elements meet all specified criteria simultaneously. This is essential when you need precise matching within individual array elements rather than across the entire array.
Advertisements
