How to Use $elemMatch in MongoDB: Syntax and Examples
Use
$elemMatch in MongoDB to find documents where at least one element in an array matches multiple conditions. It helps filter array elements by specifying criteria inside the $elemMatch object.Syntax
The $elemMatch operator is used inside a query to match documents where an array field contains at least one element that satisfies all the specified conditions.
Basic syntax:
{ arrayField: { $elemMatch: { condition1, condition2, ... } } }Here:
arrayFieldis the name of the array field in the document.$elemMatchspecifies that at least one element in the array must match all the conditions inside it.condition1, condition2, ...are the criteria that the array element must satisfy.
json
{
"arrayField": {
"$elemMatch": {
"condition1": "value1",
"condition2": "value2"
}
}
}Example
This example shows how to find documents where the grades array contains at least one element with a score greater than 80 and a type equal to "exam".
mongodb
db.students.find({
grades: {
$elemMatch: {
score: { $gt: 80 },
type: "exam"
}
}
})Output
[
{
"_id": 1,
"name": "Alice",
"grades": [
{ "score": 85, "type": "exam" },
{ "score": 70, "type": "quiz" }
]
},
{
"_id": 3,
"name": "Charlie",
"grades": [
{ "score": 90, "type": "exam" },
{ "score": 60, "type": "homework" }
]
}
]
Common Pitfalls
One common mistake is trying to match multiple conditions on different elements of the array without using $elemMatch. Without $elemMatch, MongoDB matches each condition independently on any array element, which can lead to incorrect results.
Wrong way (matches if one element has score > 80 and another element has type: "exam"):
mongodb
db.students.find({
"grades.score": { $gt: 80 },
"grades.type": "exam"
})
// This can return documents where no single grade has both conditions together.Common Pitfalls
Right way using $elemMatch to ensure both conditions apply to the same array element:
mongodb
db.students.find({
grades: {
$elemMatch: {
score: { $gt: 80 },
type: "exam"
}
}
})Key Takeaways
Use $elemMatch to match multiple conditions on the same array element in MongoDB.
Without $elemMatch, conditions on array fields may match different elements, causing wrong results.
$elemMatch syntax requires specifying the array field and the conditions inside it.
It is useful for querying arrays of objects where multiple properties must match together.
Test queries to ensure $elemMatch returns the expected documents.