本文介绍: 系统开发过程中,会有保存表达式需求比如保存数字字符字段拼接规则等。开发人员期望读取或保存这些规则时,不要被插入数据库或从数据库中读取规则时执行。或者保存模版时,也不希望讲模版中的表达式计算结果mongodb的$literal方法,为这类需求提供了便利。$literal,不会为表达式运算赋值,而是返回没有解析表达式。举例结果。

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

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

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

举例

结果

{$literal: { $add: [2, 3]}}

{ $add: [2, 3]}

{$literal: { $literal: 1}}

{ $literal: 1}

使用方法

aggregation使用用于字段后面的描述

{$literal: <value&gt;}

使用举例

返回$的字面意义

在表达式中, $代表字段路径,提供访问字段值的路径。如$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&gt;: 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}

原文地址:https://blog.csdn.net/wilsonzane/article/details/134636599

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_22620.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注