$literal (aggregation)
On this page本页内容
Definition定义
$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> }
Behavior行为
If the 如果<value>
is an expression, $literal
does not evaluate the expression but instead returns the unparsed expression.<value>
是一个表达式,$literal
不会计算该表达式,而是返回未分析的表达式。
{ $literal: { $add: [ 2, 3 ] } } | { "$add" : [ 2, 3 ] } |
{ $literal: { $literal: 1 } } | { "$literal" : 1 } |
Examples实例
Treat $
as a Literal将$
视为文字
$
as a LiteralIn 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 storeInventory
collection has the following documents:storeInventory
集合包含以下文档:
db.storeInventory.insertMany( [
{ "_id" : 1, "item" : "napkins", price: "$2.50" },
{ "_id" : 2, "item" : "coffee", price: "1" },
{ "_id" : 3, "item" : "soap", price: "$1" }
] )
db.storeInventory.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 }
Project a New Field with Value 1
投影值为1
的新字段
1
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 books
collection has the following documents:books
集合包括以下文档:
{ "_id" : 1, "title" : "Dracula", "condition": "new" }
{ "_id" : 2, "title" : "The Little Prince", "condition": "new" }
The { $literal: 1 }
expression returns a new editionNumber
field set to the value 1
:{ $literal: 1 }
表达式返回一个新的editionNumber
字段,该字段设置为值1
:
db.books.aggregate( [
{ $project: { "title": 1, "editionNumber": { $literal: 1 } } }
] )
The operation results in the following documents:操作产生以下文件:
{ "_id" : 1, "title" : "Dracula", "editionNumber" : 1 }
{ "_id" : 2, "title" : "The Little Prince", "editionNumber" : 1 }