$toInt(聚合)
定义
行为
以下表格列出了可以转换为整数的输入类型
输入类型 | 行为 |
---|---|
布尔型 | 对于 false 返回 0 。对于 true 返回 1 。 |
双精度浮点型 | 返回截断值。 截断的双精度浮点值必须位于整数的最小值和最大值之间。 您不能将截断值小于最小整数值或大于最大整数值的双精度浮点值转换为整数。 |
小数 | 返回截断值。 截断的小数值必须位于整数的最小值和最大值之间。 您不能将截断值小于最小整数值或大于最大整数值的小数值转换为整数。 |
整数 | 无操作。返回整数值。 |
长整型 | 将长整型值作为整数返回。 长整型值必须位于整数的最小值和最大值之间。 您不能将小于最小整数值或大于最大整数值的长整型值转换为整数。 |
字符串 | 将字符串的数值作为整数返回。 字符串值必须是十进制整数;例如 您不能将表示浮点数、小数或非十进制数的字符串值(例如 |
下表列出了一些转换为整数的示例
示例 | 结果 |
---|---|
$toInt: true | 1 |
$toInt: false | 0 |
$toInt: 1.99999 | 1 |
$toInt: NumberDecimal("5.5000") | 5 |
$toInt: NumberDecimal("9223372036000.000") | 错误 |
$toInt: NumberLong("5000") | 5000 |
$toInt: NumberLong("922337203600") | 错误 |
$toInt: "-2" | -2 |
$toInt: "2.5" | 错误 |
$toInt: null | null |
示例
创建以下文档的集合 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
转换为小数计算总价
// Define stage to add convertedPrice and convertedQty fields with the converted price and qty values priceQtyConversionStage = { $addFields: { convertedPrice: { $toDecimal: "$price" }, convertedQty: { $toInt: "$qty" }, } }; // Define stage to calculate total price by multiplying convertedPrice and convertedQty fields 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") }
注意
如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请使用 $convert
代替。