MongoDB聚合运算符:$toDecimal

MongoDB聚合运算符:$toDecimal

文章目录

  • [MongoDB聚合运算符:toDecimal](#MongoDB聚合运算符:toDecimal)

$toDecimal聚合运算符将指定的值转换为Decimal类型。如果指定的值为空或缺失,则返回null;如果值无法被转换为Decimal,则报错。

语法

js 复制代码
{
   $toDecimal: <expression>
}

$toDecimal接受任何有效的表达式。

$toDecimal是$convert表达式的简写形式:

js 复制代码
{ $convert: { input: <expression>, to: "Decimal" } }

使用

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

输入类型 规则
Boolean 对于True,返回Decimal128("1"),对于False返回Decimal128("0")
Double 以Decimal返回Double的值
Decimal 原样返回
Integer 以Decimal返回整数值
Long 以Decimal返回Long值
String 将字符串转换为Decimal返回,但字符串表示的必须是10进制的比如"-5.5"、"1233",非10进制的会报错,如:"0x3343"
Date 返回自与日期值对应的纪元以来的毫秒数

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

示例 结果
{$toDecimal: true} Decimal128("1")
{$toDecimal: false} Decimal128("0")
{$toDecimal: 2.5} Decimal128("2.50000000000000")
{$toDecimal: NumberInt(5)} Decimal128("5")
{$toDecimal: NumberLong(10000)} Decimal128("10000")
{$toDecimal: "-5.5"} Decimal128("-5.5")
{$toDecimal: ISODate("2018-03-27T05:04:47.890Z")} Decimal128("1522127087890")

举例

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

js 复制代码
db.orders.insertMany( [
   { _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",  qty: 5, price: 5 }
] )

下面的聚合操先orders集合的price转换为decimal,qty转换为整数,然后计算总费用:

js 复制代码
// 定义转换阶段,转换后的price和qyt字段convertedPrice和convertedQty添加到文档

priceQtyConversionStage = {
   $addFields: {
      convertedPrice: { $toDecimal: "$price" },
      convertedQty: { $toInt: "$qty" },
   }
};

//定义计算合计阶段,将convertedPrice和convertedQty相乘得到总计


totalPriceCalculationStage = {
   $project: { item: 1, totalPrice: { $multiply: [ "$convertedPrice", "$convertedQty" ] } }
};

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

执行的结果为:

js 复制代码
{ _id: 1, item: 'apple', totalPrice: Decimal128("50") },
{ _id: 2, item: 'pie', totalPrice: Decimal128("200.0") },
{ _id: 3, item: 'ice cream', totalPrice: Decimal128("9.98") },
{ _id: 4, item: 'almonds', totalPrice: Decimal128("25") }
相关推荐
李纲明25 分钟前
WordPress 提示「建立数据库连接时出错」:先核 wp-config 与数据库服务,再查表损坏与磁盘配额
数据库·wordpress·devdiy
freejackman33 分钟前
【架构篇】双遍历 + 多栈协同:手撸 SQL 血缘引擎的架构思考
java·大数据·数据库·hive·sql·架构·spark
杨云龙UP35 分钟前
TDengine 社区版磁盘空间不足故障处理 SOP:历史日志清理、日志保留策略及数据保留 200 天
数据库·时序数据库·tdengine·tsdb·历史日志清理·trim database·logkeepdays
betazhou1 小时前
MySQL Oracle官方备份工具
数据库·mysql·oracle
一万年太久。1 小时前
mysql主从复制
数据库·mysql
车载中间件通信1 小时前
[TC8测试]TCP_FLAGS_PROCESSING_06
数据库·网络协议·tcp/ip·中间件·tc8
呆萌很1 小时前
达梦数据库(DM)和MySQL核心区别
数据库
l1t1 小时前
DeepSeek总结的pgrust以光速编程:构建 Gravity 查询引擎
数据库·人工智能·postgresql
木木_Q4057733492 小时前
Oracle 增量同步配置指南:只搬变了的数据,不重复也不漏数
数据库·oracle·数据同步·数据库同步·增量同步
升鲜宝供应链及收银系统源代码服务2 小时前
Java Spring Boot 商业版 升鲜宝供应链管理系统--商品模块表与字段分析(商品管理页面业务逻辑与数据表关系分析)
数据库·生鲜配送系统排名·生鲜配送系统架构设计·b2b订货商城解决方案·生鲜配送系统源代码出售·生鲜配送系统设计源代码