Definition定义
$toDecimalConverts a value to a decimal. If the value cannot be converted to a decimal,将值转换为十进制。如果该值无法转换为十进制,则$toDecimalerrors. If the value is null or missing,$toDecimalreturns null.$toDecimal错误。如果该值为null或缺失,$toDecial将返回null。$toDecimalhas the following syntax:具有以下语法:{
$toDecimal: <expression>
}The$toDecimaltakes any valid expression.$toDecimal接受任何有效表达式。The$toDecimalis a shorthand for the following$convertexpression:$toDecimal是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "decimal" } }Tip
Behavior行为
The following table lists the input types that can be converted to a decimal:下表列出了可以转换为十进制的输入类型:
Decimal128("0") for false.false返回Decimal128("0")。Decimal128("1") for true.true返回Decimal128("1")。 | |
| Decimal | |
| |
| Date |
The following table lists some conversion to decimal examples:下表列出了一些转换为十进制的示例:
{$toDecimal: true} | Decimal128("1") |
{$toDecimal: false} | Decimal128("0") |
{$toDecimal: 2.5} | Decimal128("2.50000000000000") |
{$toDecimal: Int32(5)} | Decimal128("5") |
{$toDecimal: Long(10000)} | Decimal128("10000") |
{$toDecimal: "-5.5"} | Decimal128("-5.5") |
{$toDecimal: ISODate("2018-03-27T05:04:47.890Z")} | Decimal128("1522127087890") |
Example示例
Create a collection 使用以下文档创建集合orders with the following documents:orders:
db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, price: 10 },
{ _id: 2, item: "pie", qty: 10, price: Decimal128("20.0") },
{ _id: 3, item: "ice cream", qty: 2, price: "4.99" },
{ _id: 4, item: "almonds", qty: 5, price: 5 }
] )
The following aggregation operation on the 在计算总价之前,orders collection converts the price to a decimal and the qty to an integer before calculating the total price: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
] )
The operation returns the following documents:该操作返回以下文档:
{ _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") }
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use 如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请改用$convert instead.$converter。