In the aggregation pipeline, an expression is any value-producing construct used inside a stage. Expressions can be literals, field references, or operator expressions. They are evaluated per-document and can be nested arbitrarily.
Expression Types
// Literal value — just a constant "hello" 42 true // Field reference — prefixed with $ "$price" // value of the price field "$address.city" // dot notation for nested fields // Operator expression — { $operator: argOrArgs } { $add: ["$price", 10] } // arithmetic { $concat: ["$first", " ", "$last"] } // string { $cond: ["$active", "yes", "no"] } // conditional // Nested expressions { $multiply: [{ $add: ["$price", 5] }, 1.1] } // Inner expression is evaluated first, result passed to outer
$expr — Bridge to find() Context
$expr allows aggregation expression operators to be used inside a find() query or a $match stage where only query operators are normally allowed.
// In a regular find() — compare two fields in same doc db.orders.find({ $expr: { $gt: ["$revenue", "$cost"] } }) // In $match — use computed values as filter condition db.orders.aggregate([ { $match: { $expr: { $gt: [{ $size: "$items" }, 5] } } } ])
Expressions are available in:
$project, $addFields/$set, $match (via $expr), $group accumulators, $sort (via $meta), $filter, $map, $reduce, and $cond. Essentially, anywhere you provide a value in the pipeline.