$expr

Allows the use of aggregation expressions within the query language for complex field comparisons and calculations.

Syntax

{ $expr: { <expression> } }

Parameters

expressionobjectrequired

An 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)

Date comparison expressions

Compare date fields within the same document

Query:

db.stores.find({ $expr: { $gte: ["$lastUpdated", "$createdDate"] } })

Output:

Documents where lastUpdated is greater than or equal to createdDate

Array operations in expressions

Find stores with more than 3 promotion events

Query:

db.stores.find({ $expr: { $gt: [{ $size: "$promotionEvents" }, 3] } })

Output:

Documents where the promotionEvents array has more than 3 elements

Related