$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ <field>: { $elemMatch: { <condition1>, <condition2>, ... } } }

⚙️ Parameters

fieldThe array field to match.
conditionQuery 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏