$let (Local Variables)
Last updated: 2026-10-09
$let (Local Variables)
$let defines local variables inside aggregation expressions for use in the in expression, avoiding repeated evaluation of complex subexpressions. The syntax is { $let: { vars: { name: expression }, in: expression } }, referencing variables as $$name. It is used to compute an intermediate result once and reuse it, such as applying a discount and then computing the after-tax price. Since MongoDB 5.0, vars also accepts an array form [{ name: ..., value: ... }] that supports $ prefixed variable names.
| Category | Literal, Variable & Object |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $let: { vars: { <variable>: <expression> }, in: <expression> } }
⚙️ Parameters
| vars | Variable definitions, as an object or, since MongoDB 5.0, an array form. |
|---|---|
| in | The expression that uses the variables, referenced as $$name. |
Returns:The result of the in expression
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $let: compute a discounted price with local variables
db.orders.aggregate([
{ $project: {
finalPrice: {
$let: {
vars: { base: '$price', discount: { $multiply: ['$price', 0.1] } },
in: { $subtract: ['$$base', '$$discount'] }
}
}
} }
])
Output:
{ '_id': 1, 'finalPrice': 90 }
{ '_id': 2, 'finalPrice': 45 }
📌 Notes
- Variables are scoped to the in expression only
- Reference variables with a $$ prefix, such as $$base
- In the array form, value may be a field path expression
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is $let used for?
ADefine local variables to reuse intermediate results instead of repeating complex expressions.
QHow do I reference $let variables?
AUse $$name inside the in expression.
QCan $let variables clash with system variables?
AA $let variable shadows a system variable of the same name, so choose names carefully.