$let

Defines variables for use in a specified expression and returns the result of the expression, allowing for cleaner and more readable aggregation pipelines.

Syntax

{ $let: { vars: { <var1>: <expression1>, <var2>: <expression2>, ... }, in: <expression> } }

Parameters

varsobjectrequired

Object defining variable names and their corresponding expressions

inobjectrequired

The expression that can reference the defined variables using $$varname syntax

Examples

Calculate with variables

Define variables for cleaner calculation expressions

Query:

db.sales.aggregate([{ $project: { finalPrice: { $let: { vars: { price: "$basePrice", tax: 0.08, discount: "$discountRate" }, in: { $multiply: [{ $subtract: ["$$price", { $multiply: ["$$price", "$$discount"] }] }, { $add: [1, "$$tax"] }] } } } } }])

Output:

Documents with finalPrice calculated using defined variables for price, tax, and discount

Complex conditional logic

Use variables to simplify complex conditional expressions

Query:

db.products.aggregate([{ $project: { status: { $let: { vars: { qty: "$quantity", min: "$minimumStock", max: "$maximumStock" }, in: { $cond: { if: { $lt: ["$$qty", "$$min"] }, then: "low", else: { $cond: { if: { $gt: ["$$qty", "$$max"] }, then: "high", else: "normal" } } } } } } } }])

Output:

Documents with status field determined by quantity relative to min/max thresholds

String manipulation with variables

Define string variables for text processing operations

Query:

db.users.aggregate([{ $project: { displayName: { $let: { vars: { first: "$firstName", last: "$lastName", title: "$title" }, in: { $concat: ["$$title", " ", "$$first", " ", "$$last"] } } } } }])

Output:

Documents with displayName combining title, first name, and last name using variables

Related