← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 6 of 7

$expr

$expr lets a query compare fields of the same document or use aggregation expressions.

In this page:

  1. $expr
Syntax
javascript
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

bash
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
  1. Forgetting the $ prefix for field references
  2. Expecting indexes to always help
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.