$expr (Aggregation Expression Query)

Last updated: 2026-10-09

$expr (Aggregation Expression Query)

$expr lets query predicates use aggregation expressions — comparing multiple fields of the same document or calling aggregation operators. `{ $expr: { $gt: ['$price', '$cost'] } }` finds products priced above cost; the $ prefix references field values. $expr generally cannot use indexes (partial support since MongoDB 6.0), so use it sparingly on large collections.

CategoryElement & Evaluation
MongoDB Version3.6+
Example Languagemongosh (Shell)

📝 Syntax

{ $expr: { <aggregation expression> } }

⚙️ Parameters

aggregation expressionAn aggregation expression, e.g. { $gt: ['$price', '$cost'] }; $ references field values.

Returns:Cursor of matching documents

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $expr: products priced above cost
// $price references the field value
db.products.find({ $expr: { $gt: ['$price', '$cost'] } })

// Compare two fields for equality
db.users.find({ $expr: { $eq: ['$email', '$username'] } })

Output:

// Returns products where price exceeds cost; users whose email equals username

📌 Notes

📚 Related Tutorials

❓ FAQ

QHow does $expr compare two fields of one document?
AReference fields with $: { $expr: { $gt: ['$price', '$cost'] } }.
QCan $expr use an index?
AUsually not; since MongoDB 6.0 some cases (e.g. range comparisons) can use an index.
QWhat is the difference between $expr and $where?
A$expr uses aggregation expressions (recommended); $where runs JavaScript (slow, no indexes).
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%

🙏 帮我们做得更好

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

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