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
Selected Reading
Query nested array by more than one condition in MongoDB
To query nested array by more than one condition in MongoDB, use the $elemMatch operator. This operator matches documents that contain an array field with at least one element that satisfies all the specified query conditions.
Syntax
db.collection.find({
"arrayField": {
$elemMatch: {
"field1": "value1",
"field2": "value2"
}
}
});
Sample Data
db.demo203.insertOne({
"_id": "101",
"Name": "Chris",
"details1": [
{
"empName": "David",
"salary": "50000",
"technology": [
"MySQL",
"MongoDB"
]
},
{
"empName": "Carol",
"salary": "70000",
"technology": [
"Java",
"Spring"
]
}
]
});
{ "acknowledged": true, "insertedId": "101" }
Display all documents from a collection with the help of find() method ?
db.demo203.find();
{
"_id": "101",
"Name": "Chris",
"details1": [
{ "empName": "David", "salary": "50000", "technology": [ "MySQL", "MongoDB" ] },
{ "empName": "Carol", "salary": "70000", "technology": [ "Java", "Spring" ] }
]
}
Example: Query with Multiple Conditions
Here is how to query nested array by more than one condition ?
db.demo203.find({
details1: {
$elemMatch: {
"technology": "MySQL",
"empName": "David"
}
}
}).pretty();
{
"_id": "101",
"Name": "Chris",
"details1": [
{
"empName": "David",
"salary": "50000",
"technology": [
"MySQL",
"MongoDB"
]
},
{
"empName": "Carol",
"salary": "70000",
"technology": [
"Java",
"Spring"
]
}
]
}
Key Points
-
$elemMatchensures all conditions are satisfied by the same array element. - Without
$elemMatch, MongoDB would match conditions across different array elements. - Returns the entire document when at least one array element matches all conditions.
Conclusion
Use $elemMatch to query nested arrays with multiple conditions on the same element. This ensures all conditions are evaluated against a single array element rather than across different elements.
Advertisements
