On this page本页内容
$let
Binds variables for use in the specified expression, and returns the result of the expression.绑定变量以在指定表达式中使用,并返回表达式的结果。
The $let
expression has the following syntax:let
表达式语法如下:
{ $let: { vars: { <var1>: <expression>, ... }, in: <expression> } }
vars |
|
in |
To access variables in aggregation expressions, prefix the variable name with double dollar signs (要访问聚合表达式中的变量,请在变量名前面加上双美元符号($$
) and enclosed in quotes. $$
)并用引号括起来。For more information on expressions, see Expressions. 有关表达式的详细信息,请参阅表达式。For information on use of variables in the aggregation pipeline, see Variables in Aggregation Expressions.有关在聚合管道中使用变量的信息,请参阅聚合表达式中的变量。
$let
can access variables defined outside its expression block, including system variables.可以访问在其表达式块外部定义的变量,包括系统变量。
If you modify the values of externally defined variables in the 如果修改vars
block, the new values take effect only in the in
expression. vars
块中外部定义变量的值,则新值仅在in
表达式中生效。Outside of the 在in
expression, the variables retain their previous values.in
表达式之外,变量保留其以前的值。
In the 在vars
assignment block, the order of the assignment does not matter, and the variable assignments only have meaning inside the in
expression. vars
赋值块中,赋值顺序无关紧要,变量赋值只在in
表达式中有意义。As such, accessing a variable's value in the 因此,访问vars
assignment block refers to the value of the variable defined outside the vars
block and not inside the same vars
block.vars
赋值块中的变量值是指在vars
块外而不是在同一vars
块内定义的变量值。
For example, consider the following 例如,考虑以下$let
expression:$let
表达式:
{ $let: { vars: { low: 1, high: "$$low" }, in: { $gt: [ "$$low", "$$high" ] } } }
In the 在vars
assignment block, "$$low"
refers to the value of an externally defined variable low
and not the variable defined in the same vars
block. vars
赋值块中,"$$low"
指的是外部定义的变量low
的值,而不是同一vars
块中定义的变量。If 如果未在此low
is not defined outside this $let
expression block, the expression is invalid.$let
表达式块外定义low
,则表达式无效。
A sales
collection has the following documents:sales
集合包含以下文档:
{ _id: 1, price: 10, tax: 0.50, applyDiscount: true } { _id: 2, price: 10, tax: 0.25, applyDiscount: false }
The following aggregation uses 以下聚合使用$let
in the $project
pipeline stage to calculate and return the finalTotal
for each document:$project
管道阶段中的$let
计算并返回每个文档的finalTotal
:
db.sales.aggregate( [ { $project: { finalTotal: { $let: { vars: { total: { $add: [ '$price', '$tax' ] }, discounted: { $cond: { if: '$applyDiscount', then: 0.9, else: 1 } } }, in: { $multiply: [ "$$total", "$$discounted" ] } } } } } ] )
The aggregation returns the following results:聚合返回以下结果:
{ "_id" : 1, "finalTotal" : 9.450000000000001 } { "_id" : 2, "finalTotal" : 10.25 }