定义
$literal返回一个值而不进行解析。用于聚合管道可解释为表达式的值。
$literal表达式的语法如下:{ $literal: <value> }
行为
如果<value> 是表达式,则$literal 不会计算该表达式,而是返回未解析的表达式。
例子 | 结果 |
|---|---|
|
|
|
|
示例
将 $ 视为文字
在表达式中,美元符号 $ 的计算结果为字段路径;即提供对字段的访问权限。例如,$eq 表达式 $eq: [ "$price", "$1" ] 在文档中 price 字段中的值和 1 字段中的值之间执行相等性检查。
以下示例使用$literal 表达式将包含美元符号"$1" 的字符串视为常量值。
集合 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" } ] } } } ] )
此操作投影一个名为 costsOneDollar 的字段,该字段包含布尔值,指示 price 字段的值是否等于字符串 "$1":
{ "_id" : 1, "costsOneDollar" : false } { "_id" : 2, "costsOneDollar" : false } { "_id" : 3, "costsOneDollar" : true }
投影新字段,值为 1
$project阶段使用表达式 将<field>: 1 <field>包含在输出中。以下示例使用$literal 返回一个设立为1 值的新字段。
集合 books 包含以下文档:
db.books.insertMany([ { "_id" : 1, "title" : "Dracula", "condition": "new" }, { "_id" : 2, "title" : "The Little Prince", "condition": "new" } ])
{ $literal: 1 }表达式返回一个设立为值 的新editionNumber 1字段:
db.books.aggregate( [ { $project: { "title": 1, "editionNumber": { $literal: 1 } } } ] )
该操作生成以下文档:
{ "_id" : 1, "title" : "Dracula", "editionNumber" : 1 } { "_id" : 2, "title" : "The Little Prince", "editionNumber" : 1 }