Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$toDecimal(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toDecimal

将值转换为十进制。如果该值无法转换为十进制,则 $toDecimal出错。如果值为 null 或缺失,则$toDecimal返回 null。

$toDecimal 通过以下语法实现:

{
$toDecimal: <expression>
}

$toDecimal可采用任何有效表达式。

$toDecimal是以下$convert表达式的简写:

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

提示

另请参阅:

下表列出了可转换为十进制值的输入类型:

输入类型
行为
布尔
返回 Decimal128("0") 以表示 false
返回 Decimal128("1") 以表示 true
双精度
以十进制形式返回双精度值。
Decimal 数据类型
不操作。返回该十进制数。
整型
以十进制形式返回该整型值。
长整型
以十进制形式返回该长值。
字符串

以十进制形式返回该字符串的数值。

字符串值必须是以 10 为基数的数值(例如"-5.5""123456")。

无法转换不以 10 为基数的字符串值(例如 "0x6400"

Date
返回日期值对应的纪元起的毫秒数。

下表列出了转换为十进制值的部分示例:

例子
结果
{$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

← $toDate(聚合)

在此页面上