$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.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 3.6+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $expr: { <aggregation expression> } }
⚙️ Parameters
| aggregation expression | An 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
- The $ prefix references field values, same as in aggregation pipelines
- Generally cannot use indexes; partial support since 6.0
- Prefer plain operators whenever they can express the query
🏷️ Related Tags
💡 Related Cases
📚 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).