$elemMatch (Array Element Match)
Last updated: 2026-10-09
$elemMatch (Array Element Match)
$elemMatch matches documents where at least one array element satisfies all the given conditions. `{ scores: { $elemMatch: { $gt: 80, $lt: 90 } } }` requires a single score to be both above 80 and below 90. Without $elemMatch, multi-condition array queries match across different elements — the classic array-query pitfall.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $elemMatch: { <condition1>, <condition2>, ... } } }
⚙️ Parameters
| field | The array field to match. |
|---|---|
| condition | Query conditions the element must all satisfy. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $elemMatch: one score between 80 and 90
// The same element must satisfy both
db.students.find({ scores: { $elemMatch: { $gt: 80, $lt: 90 } } })
// Wrong: could match across different elements
// db.students.find({ scores: { $gt: 80, $lt: 90 } })
Output:
// Returns students with a single score above 80 and below 90
📌 Notes
- All conditions must hold for the same element — the core semantics
- Also works for arrays of documents: { $elemMatch: { name: 'A', score: { $gt: 90 } } }
- With a single condition it equals direct matching; with several, it is required
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $elemMatch and plain array conditions?
APlain { $gt: 80, $lt: 90 } can match across different elements; $elemMatch forces one element to satisfy both.
QCan $elemMatch match arrays of nested documents?
AYes, reference nested fields, e.g. { $elemMatch: { type: 'exam', score: { $gte: 90 } } }.
QCan $elemMatch apply to only one field?
AYes, it targets one array field; use separate $elemMatch per array field.