mongodb的$literal方法,为这类需求提供了便利。
$literal,不会为表达式运算赋值,而是返回没有解析的表达式。
使用方法
{$literal: <value>}
使用举例
返回$的字面意义
在表达式中, $代表字段路径,提供访问字段值的路径。如$eq: ["$price", "$1"]执行了字段$price, $1的等值判断。
下面的例子中,使用$literal,将带有$符号的$1作为常量来使用。
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"}]}}}
])
{"_id": 1, "costsOneDollar": false},
{"_id": 2, "costsOneDollar": false},
{"_id": 3, "costsOneDollar": true}
aggregation中,通过定义表达式<field>: 1来指定$project中返回的字段。下面的例子中, 使用$literal返回1来实现project中添加新字段。
{"_id": 1, "title": "Dracula", "condition": "new"}
{"_id": 2, "title": "The Little Prince", "condition": "new"}
db.books.aggregate( [
{$project: {"title": 1, "editionNumber": {$literal: 1}}}
])