MongoDB聚合运算符:$literal

MongoDB聚合运算符:$literal

$literal聚合运算符返回一个不进行解析的值。用于聚合管道可解释为表达式的值。

语法

{ $literal: <value> }

使用

如果<value>是一个表达式,$literal不计算表达式,而是直接返回未解析的表达式。

例如 结果
{ $literal: { $add: [ 2, 3 ] } } { "$add" : [ 2, 3 ] }
{ $literal: { $literal: 1 } } { "$literal" : 1 }

举例

把$作为文本

在表达式中,美元符号$计算结果为字段路径;即提供对现场的访问。例如,$eq表达式$eq: [ "$price", "$1" ]在文档中名为price的字段中的值与名为1的字段中的值之间执行相等性检查。

使用下面的脚本创建storeInventory集合:

db.storeInventory.insertMany( [
   { "_id" : 1, "item" : "napkins", price: "$2.50" },
   { "_id" : 2, "item" : "coffee", price: "1" },
   { "_id" : 3, "item" : "soap", price: "$1" }
] )

下面的示例使用$literal表达式,将包含美元符号"$1"的字符串视为常量值。

db.storeInventory.aggregate( [
   { $project: { costsOneDollar: { $eq: [ "$price", { $literal: "$1" } ] } } }
] )

此操作投影一个名为costOneDollar的字段,该字段保存一个布尔值,指示price字段的值是否等于字符串"$1"

{ "_id" : 1, "costsOneDollar" : false }
{ "_id" : 2, "costsOneDollar" : false }
{ "_id" : 3, "costsOneDollar" : true }

投影一个值为1的新字段

$project阶段使用表达式<field>: 1<field>包含在输出中。下面的示例使用$literal返回一个值为1的新字段。

books集合有下面的文档:

{ "_id" : 1, "title" : "Dracula", "condition": "new" }
{ "_id" : 2, "title" : "The Little Prince", "condition": "new" }

{ $literal: 1 }表达式会返回一个值为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 }

相关推荐

  1. MongoDB聚合运算符:$literal

    2024-03-31 20:24:07       34 阅读
  2. MongoDB聚合运算符:$add

    2024-03-31 20:24:07       55 阅读
  3. MongoDB聚合运算符:$arrayToObject

    2024-03-31 20:24:07       53 阅读
  4. MongoDB聚合运算符;$dateToParts

    2024-03-31 20:24:07       53 阅读
  5. MongoDB聚合运算符:$dayOfWeek

    2024-03-31 20:24:07       55 阅读
  6. MongoDB聚合运算符:$dayOfMonth

    2024-03-31 20:24:07       52 阅读
  7. MongoDB聚合运算符;$dateToString

    2024-03-31 20:24:07       48 阅读
  8. MongoDB聚合运算符:$dayOfYear

    2024-03-31 20:24:07       48 阅读
  9. MongoDB聚合运算符:$denseRank

    2024-03-31 20:24:07       42 阅读
  10. MongoDB聚合运算符:$dateTrunc

    2024-03-31 20:24:07       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 20:24:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 20:24:07       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 20:24:07       87 阅读
  4. Python语言-面向对象

    2024-03-31 20:24:07       96 阅读

热门阅读

  1. Qt之创建向导用户界面QWizard

    2024-03-31 20:24:07       41 阅读
  2. ubuntu22.04安装Fcitx5的步骤

    2024-03-31 20:24:07       34 阅读
  3. python中的re库 ,正则表达式模块

    2024-03-31 20:24:07       38 阅读
  4. 3.30蓝桥杯备赛写题心得

    2024-03-31 20:24:07       37 阅读
  5. vue知识点: v-if和v-for为何不能同时使用?

    2024-03-31 20:24:07       32 阅读
  6. Ansible

    Ansible

    2024-03-31 20:24:07      30 阅读
  7. Spark GraphX 算法实例

    2024-03-31 20:24:07       38 阅读