$expr
$expr lets a query compare fields of the same document or use aggregation expressions.
In this page:
Syntax
db.collection_name.find({ $expr: { $gt: ["$field1", "$field2"] } })
$expr
Inside $expr you write aggregation-style expressions such as { $gt: ["$spent", "$budget"] }, which compares two fields of the same document. It is powerful but may not use indexes as effectively as plain field queries.
Note:
Use $expr for field-to-field comparisons and computed conditions.
Example: $expr
test> db.budgets.insertMany([{ _id: 1, name: "A", budget: 100, spent: 120 }, { _id: 2, name: "B", budget: 100, spent: 40 }, { _id: 3, name: "C", budget: 50, spent: 50 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.budgets.find({ $expr: { $gt: ["$spent", "$budget"] } }, { name: 1, _id: 0 })
[ { name: 'A' } ]
test> db.budgets.find({ $expr: { $gte: [{ $multiply: ["$spent", 2] }, 100] } }, { name: 1, _id: 0 })
[ { name: 'A' }, { name: 'C' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the $ prefix for field references
- Expecting indexes to always help
- Mixing query and aggregation syntax
Chapter Summary
- $expr uses aggregation expressions
- Fields are referenced as "$field"
- Compares fields in one document
- May not use indexes as well
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: