MongoDB聚合运算符:$toInt

MongoDB聚合运算符:$toInt

文章目录

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

语法

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

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

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

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

使用

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

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

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

示例 结果
$toInt: true 1
$toInt: false 0
$toInt: 1.99999 1
$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: null null

举例

使用下面的脚本创建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 }
] )

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

js 复制代码
// 定义阶段,转换price为小数,转换qty为整数

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

// 定义阶段,计算总价


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") }
相关推荐
大明者省几秒前
宝塔开了端口,Ubuntu 还得开相应端口才能打通
服务器·数据库·ubuntu
Teable任意门互动1 小时前
AI原生开源多维表格有哪些?主流开源多维表格对比解析
数据库·开源·excel·钉钉·飞书·开源软件·ai-native
TDengine (老段)1 小时前
MNode 内部机制深度解析 — SDB、事务引擎与 DDL 处理全链路
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
这个DBA有点耶1 小时前
数据库上云 vs 自建:从成本到人力的三维对比与决策框架
数据库·经验分享·sql·创业创新·dba
shizhan_cloud1 小时前
MySQL 索引优化 + 慢查询日志
数据库·mysql
Drache_long1 小时前
MySQL数据库(故障排除)
数据库·mysql
2303_821287381 小时前
如何清洗SQL输入数据_使用框架内置的ORM处理数据交互
jvm·数据库·python
清风雅雨2 小时前
AI编程:OA流程明细表中多个金额字段由整数改为2位小数
数据库·ai编程
菜鸟上路_lbz2 小时前
sqlserver存储过程查询缓慢锁表分析
数据库·sqlserver
Elastic 中国社区官方博客2 小时前
在 Elasticsearch 中使用利润率与流行度加权来优化电商搜索
大数据·数据库·elasticsearch·搜索引擎·全文检索