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}
相关推荐
ybb_ymm1 天前
mysql8在linux下的默认规则修改
linux·运维·数据库·mysql
倔强的石头_1 天前
Navicat Premium 与金仓数据库融合实践:高效管理国产数据库新方案
数据库
程序新视界1 天前
为什么要尽量将MySQL表字段要设置为NOT NULL?
数据库·mysql·dba
怪兽20141 天前
SQL优化手段有哪些
java·数据库·面试
lypzcgf1 天前
FastbuildAI后端数据库模块注册分析
数据库·ai应用·ai创业·智能体平台·ai应用平台·agent平台·fastbuildai
xyy20251 天前
Spring事务的传播方式
java·数据库·spring
非凡的世界1 天前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp
yookay zhang1 天前
DM线程的管理知识学习
数据库
l1t1 天前
测试DuckDB电子表格读取插件rusty_sheet 0.2版
数据库·rust·插件·xlsx·duckdb
TiAmo zhang1 天前
SQL Server 2019实验 │ 表数据插入、修改和删除
数据库·oracle