MongoDB使用$literal获取表达式字面值

系统开发过程中,会有保存表达式的需求。比如保存数字或字符的字段拼接规则等。开发人员期望读取或保存这些规则时,不要被插入数据库或从数据库中读取规则时执行。或者保存模版时,也不希望讲模版中的表达式计算出结果。

mongodb的$literal方法,为这类需求提供了便利。

$literal,不会为表达式运算赋值,而是返回没有解析的表达式。

|-------------------------------|-------------------|
| 举例 | 结果 |
| {literal: { add: 2, 3}} | { add: \[2, 3\]} | | {literal: { literal: 1}} | { literal: 1} |

使用方法

在aggregation中使用,用于字段后面的描述。

复制代码
{$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"}]}}}
])

查询语句中的costsOneDollar字段返回布尔值,当价格时1美元时,返回true,否则返回false。

复制代码
{"_id": 1, "costsOneDollar": false},
{"_id": 2, "costsOneDollar": false},
{"_id": 3, "costsOneDollar": true}

在返回结果中添加新字段

aggregation中,通过定义表达式<field>: 1来指定project中返回的字段。下面的例子中, 使用literal返回1来实现project中添加新字段。

在books集合中,包含两条数据:

复制代码
{"_id": 1, "title": "Dracula", "condition": "new"}
{"_id": 2, "title": "The Little Prince", "condition": "new"}

使用{$literal: 1}表达式返回一个新字段editionNumber

复制代码
db.books.aggregate( [
  {$project: {"title": 1, "editionNumber": {$literal: 1}}}
])

执行后返回结果

复制代码
{"_id": 1, "title": "Dracula", "editionNumber": 1}
{"_id": 2, "title": "The Little Prince", "editionNumber": 1}
相关推荐
码农阿豪11 分钟前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?
数据库·sqlserver
bjzhang7521 分钟前
sqlsugar入门
数据库·sqlsugar
全栈陈序员2 小时前
【Git】从入门到精通(十)—— 撤销与恢复:git checkout与git restore
运维·网络·数据库·git
ss2739 小时前
为什么PostgreSQL适合AI场景?
数据库·人工智能·postgresql
瑞克-桑切斯9 小时前
7、MySQL 慢查询排查与优化实战指南
java·服务器·数据库
z06.10 小时前
MySQL索引
数据库·mysql
考虑考虑10 小时前
Posrgresql恢复.backup文件
数据库·后端·postgresql
云祺vinchin10 小时前
中小企业备份软件选型从恢复需求到总体成本评估
数据库·数据备份·中小企业备份·容灾备份软件
Zenova EdgeOS11 小时前
Go 工业边缘错误处理实战:用 errors 构建可追溯错误链
开发语言·数据库·golang
KKKlucifer11 小时前
国内数据安全服务的产品智能化转型:大模型赋能下的技术能力重构分析
大数据·数据库·重构