$toDecimal (聚合)
定义
$toDecimal
将一个值转换为十进制。如果值无法转换为十进制,
$toDecimal
错误。如果值是 null 或缺失,$toDecimal
返回 null。$toDecimal
语法如下{ $toDecimal: <expression> } $toDecimal
接受任何有效的表达式.$toDecimal
是以下$convert
表达式的简写{ $convert: { input: <expression>, to: "decimal" } }
行为
以下表格列出了可以转换为十进制的输入类型
输入类型 | 行为 |
---|---|
布尔型 | 对于 false 返回 Decimal128("0") 。对于 true 返回 Decimal128("1") 。 |
双精度浮点型 | 以十进制形式返回双精度浮点值。 |
十进制 | 无操作。返回十进制值。 |
整型 | 以十进制形式返回整型值。 |
长整型 | 以十进制形式返回长整型值。 |
字符串 | 以十进制形式返回字符串的数值。 字符串值必须是十进制数值(例如 不能将非十进制数值的字符串值转换为十进制(例如 |
日期 | 返回与日期值相对应的自从纪元以来的毫秒数。 |
以下表格列出了一些转换为十进制的示例
示例 | 结果 |
---|---|
{$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
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
转换为十进制,将 qty
转换为整数,然后计算总价
// 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
。