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}
相关推荐
月光水岸New2 小时前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu
狄加山6752 小时前
数据库基础1
数据库
我爱松子鱼2 小时前
mysql之规则优化器RBO
数据库·mysql
chengooooooo2 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
Rverdoser3 小时前
【SQL】多表查询案例
数据库·sql
Galeoto3 小时前
how to export a table in sqlite, and import into another
数据库·sqlite
人间打气筒(Ada)4 小时前
MySQL主从架构
服务器·数据库·mysql
leegong231114 小时前
学习PostgreSQL专家认证
数据库·学习·postgresql
喝醉酒的小白4 小时前
PostgreSQL:更新字段慢
数据库·postgresql
敲敲敲-敲代码4 小时前
【SQL实验】触发器
数据库·笔记·sql