How to Use $elemMatch Operator in MongoDB: Syntax and Examples
Use the
$elemMatch operator in MongoDB to find documents where at least one element in an array matches multiple criteria. It allows you to specify conditions on array elements as a single query filter inside the array field.Syntax
The $elemMatch operator is used inside a query to match documents where at least one element of an array satisfies all the specified conditions.
Its basic syntax is:
{ arrayField: { $elemMatch: { condition1, condition2, ... } } }Here:
arrayFieldis the name of the array field in the document.$elemMatchspecifies that the query applies to elements inside the array.condition1, condition2, ...are the criteria that an element must satisfy.
json
{
arrayField: {
$elemMatch: {
condition1,
condition2
}
}
}Example
This example shows how to find documents where the grades array contains at least one element with score greater than 80 and type equal to "exam".
mongodb
db.students.find({
grades: {
$elemMatch: {
score: { $gt: 80 },
type: "exam"
}
}
})Output
[
{
_id: ObjectId("..."),
name: "Alice",
grades: [
{ score: 85, type: "exam" },
{ score: 70, type: "quiz" }
]
}
]
Common Pitfalls
One common mistake is to try to match multiple conditions on array elements without using $elemMatch. This causes MongoDB to check each condition independently on the array, which may return incorrect results.
For example, this query:
{ grades: { score: { $gt: 80 }, type: "exam" } }does not ensure both conditions apply to the same array element.
The correct way is to use $elemMatch:
{ grades: { $elemMatch: { score: { $gt: 80 }, type: "exam" } } }json
{
// Incorrect: conditions apply separately
grades: {
score: { $gt: 80 },
type: "exam"
}
}
{
// Correct: both conditions apply to the same element
grades: {
$elemMatch: {
score: { $gt: 80 },
type: "exam"
}
}
}Quick Reference
| Usage | Description |
|---|---|
| { arrayField: { $elemMatch: { cond1, cond2 } } } | Match documents where an array has at least one element satisfying all conditions. |
| { arrayField: value } | Match documents where array contains the value (single condition). |
| { arrayField: { $gt: 5 } } | Match documents where array contains an element greater than 5. |
| Without $elemMatch for multiple conditions | Conditions apply independently to array elements, may give wrong results. |
Key Takeaways
Use $elemMatch to match multiple conditions on the same array element in MongoDB queries.
Without $elemMatch, conditions on arrays apply independently and may return incorrect matches.
$elemMatch works inside the query filter on array fields to specify element-level criteria.
It is useful for querying arrays of objects where multiple fields must match together.
Always test queries to ensure conditions apply as expected to array elements.