On this page本页内容
$literal
Returns a value without parsing. Use for values that the aggregation pipeline may interpret as an expression.返回值而不进行分析。用于聚合管道可能解释为表达式的值。
The $literal expression has the following syntax:$literal表达式语法如下:
{ $literal: <value> }
If the 如果<value> is an expression, $literal does not evaluate the expression but instead returns the unparsed expression.<value>是表达式,$literal不会计算表达式,而是返回未分析的表达式。
| Example | Result |
|---|---|
{ $literal: { $add: [ 2, 3 ] } } | { "$add" : [ 2, 3 ] } |
{ $literal: { $literal: 1 } } | { "$literal" : 1 } |
$ as a Literal$视为文字In expression, the dollar sign 在表达式中,美元符号$ evaluates to a field path; i.e. provides access to the field. $计算为字段路径;即提供了访问该字段的权限。For example, the 例如,$eq expression $eq: [ "$price", "$1" ] performs an equality check between the value in the field named price and the value in the field named 1 in the document.$eq表达式$eq: [ "$price", "$1" ]在名为price的字段中的值与文档中名为1的字段中值之间执行相等性检查。
The following example uses a 以下示例使用$literal expression to treat a string that contains a dollar sign "$1" as a constant value.$literal表达式将包含美元符号"$1"的字符串视为常量值。
A collection 集合records has the following documents:records包含以下文档:
{ "_id" : 1, "item" : "abc123", price: "$2.50" }
{ "_id" : 2, "item" : "xyz123", price: "1" }
{ "_id" : 3, "item" : "ijk123", price: "$1" }
db.records.aggregate( [
{ $project: { costsOneDollar: { $eq: [ "$price", { $literal: "$1" } ] } } }
] )
This operation projects a field named 此操作投射一个名为costsOneDollar that holds a boolean value, indicating whether the value of the price field is equal to the string "$1":costsOneDollar的字段,该字段包含一个布尔值,指示price字段的值是否等于字符串"$1":
{ "_id" : 1, "costsOneDollar" : false }
{ "_id" : 2, "costsOneDollar" : false }
{ "_id" : 3, "costsOneDollar" : true }
11投影新字段The $project stage uses the expression <field>: 1 to include the <field> in the output. $project阶段使用表达式<field>:1在输出中包含<field>。The following example uses the 以下示例使用$literal to return a new field set to the value of 1.$literal返回值为1的新字段。
A collection 集合bids has the following documents:bids包含以下文件:
{ "_id" : 1, "item" : "abc123", condition: "new" }
{ "_id" : 2, "item" : "xyz123", condition: "new" }
The following aggregation evaluates the expression 以下聚合计算表达式item: 1 to mean return the existing field item in the output, but uses the { $literal: 1 } expression to return a new field startAt set to the value 1:item: 1表示返回输出中的现有字段item,但使用{ $literal: 1 }表达式返回设置为值1的新字段startAt:
db.bids.aggregate( [
{ $project: { item: 1, startAt: { $literal: 1 } } }
] )
The operation results in the following documents:该操作产生以下文档:
{ "_id" : 1, "item" : "abc123", "startAt" : 1 }
{ "_id" : 2, "item" : "xyz123", "startAt" : 1 }