$expr
Allows the use of aggregation expressions within the query language for complex field comparisons and calculations.
Syntax
{ $expr: { <expression> } }
Parameters
expression
objectrequiredAn aggregation expression that can include field references, operators, and computations
Examples
Compare two fields in same document
Find stores where full-time staff is greater than part-time staff
Query:
db.stores.find({ $expr: { $gt: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] } })
Output:
Documents where fullTime field value exceeds partTime field value
Arithmetic calculations in queries
Find stores where total sales exceed twice the sum of individual category sales
Query:
db.stores.find({ $expr: { $gt: ["$sales.totalSales", { $multiply: [{ $sum: "$sales.salesByCategory.totalSales" }, 2] }] } })
Output:
Documents where totalSales is greater than double the sum of category sales
Conditional expressions with $cond
Find stores based on conditional logic using staff size categories
Query:
db.stores.find({ $expr: { $gt: [{ $cond: { if: { $gte: ["$staff.totalStaff.fullTime", 10] }, then: 1, else: 0 } }, 0] } })
Output:
Documents where conditional expression evaluates to true (stores with 10+ full-time staff)