What is the MongoDB aggregation $expr operator?
Why Interviewers Ask This
Mid-level MongoDB roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
The $expr operator allows use of aggregation expressions within the $match stage (and $filter, $lookup pipeline conditions). It enables comparing two fields within the same document, something regular query operators ($eq, $gt) cannot do. Comparing two document fields: db.orders.find({ $expr: { $gt: ["$actualRevenue", "$estimatedRevenue"] } }) — finds orders where actual exceeds estimated revenue. Without $expr, you can't compare two fields from the same document in a query. Complex expressions in $match: db.products.find({ $expr: { $and: [ { $gte: ["$discount", 0.1] }, { $lt: ["$price", { $multiply: ["$originalPrice", 0.8] }] } ] } }) — products with 10%+ discount AND price less than 80% of original. Using $expr in $lookup pipeline conditions: { $lookup: { from: "inventory", let: { productId: "$productId", quantity: "$quantity" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$$productId", "$product_id"] }, { $gte: ["$stock", "$$quantity"] } ] } } } ], as: "available_stock" } }. $expr vs regular query operators: regular operators ({ age: { $gt: 18 } }) compare field to literal; $expr compares field to field or evaluates aggregation expressions. Index usage with $expr: $expr can use indexes but may be less optimal than regular query operators — profile queries using $expr to verify index usage.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a MongoDB codebase.
Previous
What is the MongoDB connection string format?
Next
How does MongoDB replication work internally?