MongoDB聚合运算符:$toInt

MongoDB聚合运算符:$toInt


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

语法

{
   $toInt: <expression>
}

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

$toInt$convert表达式的简写形式:

{ $convert: { input: <expression>, to: "int" } }

使用

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

输入类型规则
Boolean对于True,返回1,对于False返回0
Decimal返回截断值。截断的小数值必须在整数的最小值和最大值范围内。如果截断值小于最小整数值或大于最大整数值,则无法转换
Double返回截断值。截断的双数值必须在整数的最小值和最大值范围内。如果截断值小于最小整数值或大于最大整数值,则无法转换
Integer直接返回
Long以整数返回Long值,Long值必须在整数的最小值和最大值范围内。如果截断值小于最小整数值或大于最大整数值,则无法转换
String将字符串转换为整数返回,但字符串表示的必须是10进制的整数比如"-5"、“1233”,非10进制的会报错,如:“0x3343”

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

示例结果
$toInt: true1
$toInt: false0
$toInt: 1.999991
$toInt: NumberDecimal("5.5000")5
$toInt: NumberDecimal("9223372036000.000")Error
$toInt: NumberLong("5000")5000
$toInt: NumberLong("922337203600")Error
$toInt: "-2"-2
$toInt: "2.5"Error
$toInt: nullnull

举例

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

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 }
] )

下面的聚合操将qty集转换为整数,将Price转换为小数,并计算总价格:

// 定义阶段,转换price为小数,转换qty为整数

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

// 定义阶段,计算总价


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

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

执行的结果为:

{ _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") }
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值