MongoDB-CN-Manual
  • MongoDB中文手册|官方文档中文版
  • MongoDB用户手册说明
  • MongoDB简介
    • 入门
    • 数据库和集合
      • 视图
      • 按需物化视图
      • 封顶集合
      • 时间序列集合
    • 文档
    • BSON类型
      • Comparison and Sort Order
      • MongoDB Extended JSON (v2)
      • MongoDB Extended JSON (v1)
  • 安装 MongoDB
    • 安装MongoDB社区版
      • 在Linux上安装MongoDB社区版
      • 在macOS上安装MongoDB社区版
      • 在Windows上安装MongoDB社区版
    • 安装MongoDB企业版
      • 在Linux上安装MongoDB企业版
      • 在Mac OS安装MongoDB企业版
      • 在Windows安装MongoDB企业版
      • 使用Docker安装MongoDB企业版
    • 将社区版MongoDB升级到企业版MongoDB
    • 验证MongoDB软件包的完整性
  • The mongo Shell
    • 配置mongo Shell
    • 使用 mongo Shell帮助
    • 为mongo Shell编写脚本
    • mongo Shell中的数据类型
    • mongo Shell 快速参考
  • MongoDB CRUD操作
    • 插入文档
      • 插入方法
    • 查询文档
      • 在mongo Shell中迭代游标
      • 从查询返回的项目字段
      • 查询嵌入式文档数组
      • 查询数组
      • 查询空字段或缺少字段
      • 查询嵌入/嵌套文档
    • 更新文档
      • 更新方法
      • 聚合管道更新
    • 删除文档
      • 删除方法
    • 地理空间查询
      • 用地理空间查询查找餐馆
      • GeoJSON对象
    • 批量写入操作
    • 可重试写入
    • 可重试读取
    • SQL到MongoDB的映射图表
    • 文本搜索
      • 文本索引
      • 文本索引操作
      • 集合管道中的文本索引
      • 文本索引语言
    • Read Concern读关注
      • 读关注 "local"
      • 读关注 "available"
      • 读关注 "majority"
      • 读关注 "linearizable"
      • 读关注 "snapshot"
    • Write Concern写关注
    • MongoDB CRUD概念
      • 原子性和事务
      • 读隔离性,一致性和近因性
        • 因果一致性和读写关注
      • 分布式查询
      • 通过findAndModify进行线性化读取
      • 查询计划
      • 查询优化
        • 评估当前操作性能
        • 优化查询性能
        • 写操作性能
        • 说明结果
      • 分析查询表现
      • Tailable 游标
  • MongoDB聚合
    • 聚合管道
      • 聚合管道优化
      • 聚合管道限制
      • 聚合管道和分片集合
      • 使用 Zip Code 数据集进行聚合
      • 使用用户首选项数据进行聚合
    • Map-Reduce
      • Map-Reduce 和分片集合
      • Map-Reduce 并发
      • Map-Reduce 示例
      • 执行增量 Map-Reduce
      • 对 Map Function 进行故障排除
      • 排除 Reduce Function 问题
      • Map-Reduce转换到聚合管道
    • 聚合参考
      • 聚合管道快速参考
      • 聚合命令
      • 聚合命令对比
      • 聚合表达式中的变量
      • SQL 到聚合映射图表
  • MongoDB数据模型
    • 数据建模介绍
    • 模式验证
    • 数据模型设计
      • 一对一嵌套关系模型
  • MongoDB事务
  • MongoDB事务
    • 驱动程序 API
    • 生产注意事项
    • 生产注意事项 (分片集群)
    • 事务操作
  • MongoDB索引
    • 单字段索引
    • 复合索引
    • 多键索引
      • 多键索引范围
    • 文本索引
      • 为文本索引指定语言
      • 指定文本索引的名称
      • 用权重控制搜索结果
      • 限制扫描条目的数量
    • 通配符索引
      • 通配符索引限制
    • 2dsphere 索引
      • 查询一个2dsphere索引
    • 2d 索引
      • 创建一个2d索引
      • 查询一个2d索引
      • 2d索引内部
      • 使用球面几何计算距离
    • geoHaystack 索引
      • 创建Haystack索引
      • 查询Haystack索引
    • 哈希索引
    • 索引特性
      • TTL 索引
        • 通过设置TTL使集合中的数据过期
      • 唯一索引
      • 部分索引
      • 不分大小写索引
      • Sparse 索引
    • 在填充的集合上建立索引
      • 在副本集上建立滚动索引
      • 在分片群集上建立滚动索引
    • 索引交集
    • 管理索引
    • 衡量索引使用
    • 索引策略
      • 创建索引来支持查询
      • 使用索引对查询结果进行排序
      • 确保索引适合RAM
      • 创建以确保选择性的查询
    • 索引参考
  • MongoDB安全
    • 安全检查列表
    • 启用访问控制
    • 身份验证
      • 用户
        • 添加用户
        • 权限认证机制
          • SCRAM
            • 用x.509证书来认证客户端
    • 审计
      • 配置审计过滤器
      • 配置审计
      • 系统事件审计消息
    • 网络和配置强化
    • 安全参考
      • system.roles集合
      • system.users集合
      • 资源文档
      • 权限操作
    • 附录
      • 附录-A-用于测试的 OpenSSl CA 证书
      • 附录-B-用于测试的OpenSSL服务器证书
      • 附录-C-用于测试的OpenSSL客户端证书
  • Change Streams变更流
    • 变更流生产建议
    • 变更事件
  • MongoDB复制
    • 副本集成员
    • 副本集日志
    • 副本集数据同步
    • 副本集部署架构
    • 副本集成员配置教程
    • 副本集维护教程
    • MongoDB复制参考
  • MongoDB分片
    • 分片集群组件
    • 分片键
    • 哈希分片
    • 范围分片
    • 区
      • 管理分片区
      • 按位置细分数据
      • 用于更改SLA或SLO的分层硬件
      • 按应用或客户细分数据
      • 仅插入工作负载的分布式本地写入
      • 管理分片区
    • 使用块进行数据分区
      • 在分片集群中拆分数据块
    • 分片管理
      • 查看集群设置
    • 重启一个分片集群
    • [把一个分片集群迁移到不同的硬件](fen-pian/migrate-a -sharded-cluster-to-different-hardware.md)
    • 分片参考
  • MongoDB管理
    • 产品说明
    • 操作检查列表
    • 开发检查列表
    • 配置和维护
    • 性能
    • 数据中心意识
      • MongoDB部署中的工作负载隔离
      • 区
        • 管理分片区
        • 按位置细分数据
        • 用于更改SLA或SLO的分层硬件
        • 按应用或客户细分数据
        • 仅插入工作负载的分布式本地写入
        • 管理分片区
    • MongoDB备份方法
    • MongoDB监控
  • MongoDB存储
    • 存储引擎
      • WiredTiger 存储引擎
      • 内存存储引擎
    • 日志记录
      • 管理日志记录
        • GridFS
        • FAQ:MongoDB 存储
  • MongoDB参考
    • 运算符
      • 查询与映射运算符
        • 比较查询运算符
          • $eq
          • $gt
          • $gte
          • $in
          • $lt
          • $lte
          • $ne
          • $nin
        • 逻辑查询运算符
          • $and
          • $not
          • $nor
          • $or
        • 元素查询运算符
        • 评估查询运算符
        • 地理空间查询运算符
        • 数组查询运算符
        • 按位查询运算符
        • $comment
        • 映射运算符
      • 更新运算符
        • 字段更新运算符
        • 数组更新运算符
        • 按位更新运算符
      • 聚合管道阶段
      • 聚合管道操作符
        • $abs (aggregation)
        • $acos (aggregation)
        • $acosh (aggregation)
        • $add (aggregation)
        • $addToSet (aggregation)
        • $allElementsTrue (aggregation)
        • $and (aggregation)
        • $anyElementTrue (aggregation)
        • $arrayElemAt (aggregation)
        • $arrayToObject (aggregation)
        • $asin (aggregation)
        • $asinh (aggregation)
        • $atan (aggregation)
        • $atan2 (aggregation)
        • $atanh (aggregation)
        • $avg (aggregation)
        • $ceil (aggregation)
        • $cmp (aggregation)
        • $concat (aggregation)
        • $concatArrays (aggregation)
        • $cond (aggregation)
        • $convert (aggregation)
        • $cos (aggregation)
        • $dateFromParts (aggregation)
        • $dateToParts (aggregation)
        • $dateFromString (aggregation)
        • $literal (aggregation)
      • 查询修饰符
    • 数据库命令
      • 聚合命令
      • 地理空间命令
      • 查询和写操作命令
      • 查询计划缓存命令
      • 认证命令
      • 用户管理命令
      • 角色管理命令
      • 复制命令
      • 分片命令
      • 会话命令
      • 管理命令
      • 诊断命令
      • 免费监控命令
      • 系统事件审计命令
    • mongo Shell 方法
      • 集合方法
        • db.collection.aggregate()
        • db.collection.bulkWrite()
        • db.collection.copyTo()
        • db.collection.count()
        • db.collection.countDocuments()
        • db.collection.estimatedDocumentCount()
        • db.collection.createIndex()
        • db.collection.createIndexes()
        • db.collection.dataSize()
        • db.collection.deleteOne()
        • db.collection.deleteMany()
        • db.collection.distinct()
        • db.collection.drop()
        • db.collection.dropIndex()
        • db.collection.dropIndexes()
        • db.collection.ensureIndex()
        • db.collection.explain()
        • db.collection.find()
        • db.collection.findAndModify()
        • db.collection.findOne()
        • db.collection.findOneAndDelete()
        • db.collection.findOneAndReplace()
        • db.collection.findOneAndUpdate()
        • db.collection.getIndexes()
        • db.collection.getShardDistribution()
        • db.collection.getShardVersion()
        • db.collection.insert()
        • db.collection.insertOne()
        • db.collection.insertMany()
        • db.collection.isCapped()
        • db.collection.latencyStats()
        • db.collection.mapReduce()
        • db.collection.reIndex()
        • db.collection.remove()
        • db.collection.renameCollection()
        • db.collection.replaceOne()
        • db.collection.save()
        • db.collection.stats()
        • db.collection.storageSize()
        • db.collection.totalIndexSize()
        • db.collection.totalSize()
        • db.collection.update()
        • db.collection.updateOne()
        • db.collection.updateMany()
        • db.collection.watch()
        • db.collection.validate()
    • MongoDB中的限制与阈值
    • MongoDB系统集合
    • 词汇表
    • 默认的MongoDB端口
    • 默认的MongoDB读/写关注
    • 服务器会话
  • MongoDB FAQ
    • FAQ: MongoDB基础知识
    • FAQ: MongoDB索引
    • FAQ: MongoDB并发
    • FAQ: MongoDB分片
    • FAQ: MongoDB复制和副本集
    • FAQ: MongoDB存储
    • FAQ: MongoDB诊断
  • MongoDB 版本管理
  • 联系我们
    • Tapdata Cloud
    • MongoDB中文社区
    • 社区合作伙伴—锦木信息
由 GitBook 提供支持
在本页
  • 定义
  • 行为
  • 转换为布尔值
  • 转换为整数
  • 转换为十进制
  • 转换为Double
  • 转换为Long
  • 转换为日期
  • 转换成的ObjectId
  • 转换为字符串
  • 例子
  1. MongoDB参考
  2. 运算符
  3. 聚合管道操作符

$convert (aggregation)

上一页$cond (aggregation)下一页$cos (aggregation)

最后更新于3年前

在本页面

定义

$convert

版本4.0中的新功能。

将值转换为指定的类型。

$convert具有以下语法:

{
   $convert:
      {
         input: <expression>,
         to: <type expression>,
         onError: <expression>,  // Optional.
         onNull: <expression>    // Optional.
      }
}

在$convert需要具有以下字段的文档:

字段
描述

input

参数可以是任何有效的表达式。有关表达式的更多信息,请参见表达式。

to

该参数可以是任何可解析为以下数字或字符串标识符之一的有效表达式,见下表

onError

可选的。在转换过程中遇到错误(包括不支持的类型转换)时返回的值。参数可以是任何有效的表达式。 如果未指定,则操作在遇到错误时将引发错误并停止。

onNull

可选的。如果input为null或缺失,则返回的值。参数可以是任何有效的表达式。 如果未指定,$convert则如果inputnull为null或缺少,则返回null 。

字符串标识符
数值标识符
笔记

“double”

1

有关转换为double的更多信息,请参见 转换为Double。

“string”

2

有关转换为字符串的更多信息,请参见 转换为字符串。

“objectId”

7

有关转换为objectId的更多信息,请参见 转换为ObjectId。

“bool”

8

有关转换为布尔值的更多信息,请参见 转换为布尔值。

“date”

9

有关转换为日期的更多信息,请参见 转换为日期。

“int”

16

有关转换为整数的更多信息,请参见 转换为整数。

“long”

18

有关转换为long的更多信息,请参见 转换为long。

“decimal”

19

有关转换为十进制的更多信息,请参见 转换为十进制。

除$convert之外,当默认的“ onError”和“ onNull”行为可以接受时,MongoDB还提供以下聚合运算符作为速记:

  • $toBool

  • $toDate

  • $toDecimal

  • $toDouble

  • $toInt

  • $toLong

  • $toObjectId

  • $toString

行为

转换为布尔值

下表列出了可以转换为布尔值的输入类型:

输入类型
行为

Boolean

无操作,返回布尔值。

Double

如果不为零,则返回true。 如果为零,则返回false。

Decimal

如果不为零,则返回true。 如果为零,则返回false。

Integer

如果不为零,则返回true。 如果为零,则返回false。

Long

如果不为零,则返回true。 如果为零,则返回false。

ObjectId

返回true。

String

返回true。

Date

返回true。

下表列出了一些转换为布尔值的示例:

例子
结果

{ input: true, to: "bool"}

true

{ input: false, to: "bool" }

false

{ input: 1.99999, to: "bool" }

true

{ input: NumberDecimal("5"), to: "bool"}

true

{ input: NumberDecimal("0"), to: "bool"}

false

{ input: 100, to: "bool" }

true

{ input: ISODate("2018-03-26T04:38:28.044Z"), to: "bool" }

true

{ input: "hello", to: "bool" }

true

{ input: "false", to: "bool" }

true

{ input: "", to: "bool" }

true

{ input: null, to: "bool" }

Null

也可以看看

$toBool

转换为整数

下表列出了可以转换为整数的输入类型:

输入类型
行为

Boolean

返回0的 false。 返回1的true。

Double

返回截断值。 截断后的double值必须在整数的最大值和最小值之内。 您不能转换其截断值小于最小整数值或大于最大整数值的double值。

Decimal

返回截断值。 截断的十进制值必须在整数的最大值和最小值之内。 您不能转换截断值小于最小整数值或大于最大整数值的十进制值。

Integer

无操作,返回整数值。

Long

以整数形式返回long值。 long值必须落在整数的最小值和最大值之间。 您不能转换小于最小整数值或大于最大整数值的长值。

String

以整数形式返回字符串的数值。 字符串值必须是base 10的整数(例如 "-5","123456")并落在整数的最小值和最大值之内。 不能转换浮点数、十进制数或非base10数字的字符串值(例如"-5.0","0x6400")或低于整数的最小和最大值的值。

下表列出了一些转换为整数的示例:

例子
结果

{ input: true, to: "int"}

1

{ input: false, to: "int" }

0

{ input: 1.99999, to: "int" }

1

{ input: NumberDecimal("5.5000"), to: "int"}

5

{ input: NumberDecimal("9223372036000.000"), to: "int"}

Error

{ input: NumberDecimal("9223372036000.000"), to: "int", onError: "Could not convert to type integer." }

“Could not convert to type integer.”

{ input: NumberLong("5000"), to: "int"}

5000

{ input: NumberLong("922337203600"), to: "int"}

Error

{ input: "-2", to: "int" }

-2

{ input: "2.5", to: "int" }

Error

{ input: null, to: "int" }

null

也可以看看

$toInt操作符。

转换为十进制

下表列出了可以转换为十进制的输入类型:

输入类型
行为

Boolean

false返回NumberDecimal("0") true返回NumberDecimal("1")

Double

返回双精度值作为十进制数。

Decimal

无操作,返回小数。

Integer

以小数形式返回int值。

Long

返回long值(十进制)。

String

以十进制形式返回字符串的数值。 字符串值必须是base 10数字值(例如 "-5.5","123456")。 您不能转换非base10数字的字符串值 (例如"0x6400")

Date

返回自与日期值相对应的纪元以来的毫秒数。

下表列出了一些转换为十进制的示例:

例子
结果

{ input: true, to: "decimal"}

NumberDecimal(“1”)

{ input: false, to: "decimal" }

NumberDecimal(“0”)

{ input: 2.5, to: "decimal" }

NumberDecimal(“2.50000000000000”)

{ input: NumberInt(5), to: "decimal"}

NumberDecimal(“5”)

{ input: NumberLong(10000), to: "decimal"}

NumberDecimal(“10000”)

{ input: "-5.5", to: "decimal" }

NumberDecimal(“-5.5”)

{ input: ISODate("2018-03-27T05:04:47.890Z"), to: "decimal" }

NumberDecimal(“1522127087890”)

也可以看看

$toDecimal

转换为Double

下表列出了可以转换为双精度型的输入类型:

输入类型
行为

Boolean

false返回的NumberLong(0) true返回的NumberLong(1)

Double

无操作,返回双精度型。

Decimal

以双精度值返回十进制值。 小数值必须在双精度的最小值和最大值之内。 不能转换一个小于最小双精度值或大于最大双精度值的十进制值。

Integer

以双精度值返回int值。

Long

将long值作为双精度值返回。

String

以双精度值形式返回字符串的数值。 字符串值必须是一个以10为基的数值(例如:"-5.5", "123456"),并落在双精度的最小值和最大值之内。 不能转换非base10数字的字符串值。“0x6400”)或低于双精度的最小值和最大值的值。

Date

返回自纪元以来对应于日期值的毫秒数。

下表列出了一些转换为Double的示例:

例子
结果

{ input: true, to: "double"}

1

{ input: false, to: "double" }

0

{ input: 2.5, to: "double" }

2.5

{ input: NumberInt(5), to: "double"}

5

{ input: NumberLong(10000), to: "double"}

10000

{ input: "-5.5", to: "double" }

-5.5

{ input: "5e10", to: "double" }

50000000000

{ input: "5e550", to: "double", onError: "Could not convert to type double." }

“Could not convert to type double.”

{ input: ISODate("2018-03-27T05:04:47.890Z"), to: "double" }

1522127087890

也可以看看

$toDouble

转换为Long

下表列出了可以转换为long的输入类型:

输入类型
行为

Boolean

false返回0 true返回1

Double

返回截断值。 截断后的double值必须长时间处于最小值和最大值之间。 不能转换其截断值小于最小长整型值或大于最大长整型值的双精度值。

Decimal

返回截断值。 截断的十进制值必须在Long的最大值和最小值之间。 不能转换截断值小于最小长值或大于最大长值的十进制值。

Integer

以long形式返回int值。

Long

无操作。返回Long值。

String

返回字符串的数值。 字符串值必须是base10长度的(例如。“-5”,“123456”),并落在Long最大值和最小值之内。 不能转换浮点数、十进制数或非base10数字的字符串值。(例如 “-5.0”、“0x6400”)或处于Long最小和最大值之外的值。

Date

将日期转换为纪元以来的毫秒数。

下表列出了一些到长示例的转换:

例子
结果

{ input: true, to: "long" }

NumberLong(“1”)

{ input: false, to: "long" }

NumberLong(“0”)

{ input: 1.99999, to: "long" }

NumberLong(“1”)

{ input: NumberDecimal("5.5000"), to: "long" }

NumberLong(“5”)

{ input: NumberDecimal("9223372036854775808.0"), to: "long" }

Error

{ input: NumberDecimal("9223372036854775808.000"), to: "long", onError: "Could not convert to type long." }

“Could not convert to type long.”

{ input: NumberInt(8), to: "long" }

NumberLong(8)

{ input: ISODate("2018-03-26T04:38:28.044Z"), to: "long" }

NumberLong(“1522039108044”)

{ input: "-2", to: "long" }

NumberLong(“-2”)

{ input: "2.5", to: "long" }

Error

{ input: null, to: "long" }

null

也可以看看

$toLong

转换为日期

下表列出了可以转换为日期的输入类型:

输入类型
行为

Double

返回一个日期,该日期对应于被截断的双精度值所表示的毫秒数。 正值对应自1970年1月1日以来的毫秒数。 负数对应于1970年1月1日之前的毫秒数。

Decimal

返回一个日期,该日期对应于被截断的十进制值所表示的毫秒数。 正值对应自1970年1月1日以来的毫秒数。 负数对应于1970年1月1日之前的毫秒数。

Long

返回一个日期,该日期对应于Long值所表示的毫秒数。 正值对应自1970年1月1日以来的毫秒数。 负数对应于1970年1月1日之前的毫秒数。

String

返回与日期字符串对应的日期。 字符串必须是一个有效的日期字符串,例如: 1. “2018-03-03” 2. “2018-03-03T12:00:00Z” 3. “2018-03-03T12:00:00+0500”

ObjectId

返回与ObjectId的时间戳相对应的日期。

下表列出了一些转换日期的示例:

例子
结果

{ input: 120000000000.5, to: "date"}

ISODate(“1973-10-20T21:20:00Z”)

{ input: NumberDecimal("1253372036000.50"), to: "date"}

ISODate(“2009-09-19T14:53:56Z”)

{ input: NumberLong("1100000000000"), to: "date"}

ISODate(“2004-11-09T11:33:20Z”)

{ input: NumberLong("-1100000000000"), to: "date"}

ISODate(“1935-02-22T12:26:40Z”)

{ input: ObjectId("5ab9c3da31c2ab715d421285"), to: "date" }

ISODate(“2018-03-27T04:08:58Z”)

{ input: "2018-03-03", to: "date" }

ISODate(“2018-03-03T00:00:00Z”)

{ input: "2018-03-20 11:00:06 +0500", to: "date" }

ISODate(“2018-03-20T06:00:06Z”)

{ input: "Friday", to: "date" }

Error

{ input: "Friday", to: "date", onError: "Could not convert to type date." }

“Could not convert to type date.”

也可以看看

$toDate操作符, $dateFromString

转换成的ObjectId

下表列出了可以转换为ObjectId的输入类型:

输入类型
行为

String

返回长度为24的十六进制字符串的ObjectId。 不能转换长度为24的十六进制字符串以外的字符串值。

下表列出了一些转换日期的示例:

例子
结果

{ input: "5ab9cbfa31c2ab715d42129e", to: "objectId"}

ObjectId(“5ab9cbfa31c2ab715d42129e”)

{ input: "5ab9cbfa31c2ab715d42129", to: "objectId"}

Error

{ input: "5ab9cbfa31c2ab715d42129", to: "objectId", onError: "Could not convert to type ObjectId." }

“Could not convert to type ObjectId.”

也可以看看

$toObjectId操作符。

转换为字符串

下表列出了可以转换为字符串的输入类型:

输入类型
行为

Boolean

以字符串形式返回布尔值。

Double

以字符串形式返回双精度值。

Decimal

以字符串形式返回十进制值。

Integer

以字符串的形式返回整数值。

Long

以字符串形式返回长值。

ObjectId

以十六进制字符串的形式返回ObjectId值。

String

无操作。返回字符串值。

Date

以字符串形式返回日期。

下表列出了一些转换为字符串的示例:

例子
结果

{ input: true, to: "string" }

“true”

{ input: false, to: "string" }

“false”

{ input: 2.5, to: "string"}

“2.5”

{ input: NumberInt(2), to: "string"}

“2”

{ input: NumberLong(1000), to: "string"}

“1000”

{ input: ObjectId("5ab9c3da31c2ab715d421285"), to: "string" }

“5ab9c3da31c2ab715d421285”

{ input: ISODate("2018-03-27T16:58:51.538Z"), to: "string" }

{ input: ISODate("2018-03-27T16:58:51.538Z"), to: "string" }“2018-03-27T16:58:51.538Z”

也可以看看

$toString操作符。 $dateToString

例子

orders使用以下文档创建一个集合:

db.orders.insert( [
   { _id: 1, item: "apple", qty: 5, price: 10 },
   { _id: 2, item: "pie", qty: 10, price: NumberDecimal("20.0") },
   { _id: 3, item: "ice cream", qty: 2, price: "4.99" },
   { _id: 4, item: "almonds" },
   { _id: 5, item: "bananas", qty: 5000000000, price: NumberDecimal("1.25") }
] )

集合上的以下汇总操作orders会将转换price为小数:

// 定义使用转换后的价格和数量值添加convertedPrice和convertedQty字段的阶段
// 如果没有price或qty值,则返回十进制值或整数值
// 如果不能转换价格或数量值,将返回一个字符串

priceQtyConversionStage = {
   $addFields: {
      convertedPrice: { $convert: { input: "$price", to: "decimal", onError: "Error", onNull: NumberDecimal("0") } },
      convertedQty: { $convert: {
         input: "$qty", to: "int",
         onError:{$concat:["Could not convert ", {$toString:"$qty"}, " to type integer."]},
         onNull: NumberInt("0")
      } },
   }
};

totalPriceCalculationStage = {
   $project: { totalPrice: {
     $switch: {
        branches: [
          { case: { $eq: [ { $type: "$convertedPrice" }, "string" ] }, then: "NaN" },
          { case: { $eq: [ { $type: "$convertedQty" }, "string" ] }, then: "NaN" },
        ],
        default: { $multiply: [ "$convertedPrice", "$convertedQty" ] }
     }
} } };

db.orders.aggregate( [
   priceQtyConversionStage,
   totalPriceCalculationStage
])

该操作返回以下文档:

{ "_id" : 1, "totalPrice" : NumberDecimal("50.0000000000000") }
{ "_id" : 2, "totalPrice" : NumberDecimal("200.0") }
{ "_id" : 3, "totalPrice" : NumberDecimal("9.98") }
{ "_id" : 4, "totalPrice" : NumberDecimal("0") }
{ "_id" : 5, "totalPrice" : "NaN" }

译者:李冠飞

校对:

定义
行为
例子