$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.

CategoryLiteral, Variable & Object
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $let: { vars: { <variable>: <expression> }, in: <expression> } }

⚙️ Parameters

varsVariable definitions, as an object or, since MongoDB 5.0, an array form.
inThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏