On this page本页内容
$toDecimal¶New in version 4.0.版本4.0中的新功能。
Converts a value to a decimal. If the value cannot be converted to a decimal, $toDecimal errors. If the value is null or missing, $toDecimal returns null.
$toDecimal has the following syntax:语法如下所示:
The $toDecimal takes any valid expression.
The $toDecimal is a shorthand for the following $convert expression:
See also参阅
The following table lists the input types that can be converted to a decimal:
| Input Type | Behavior |
|---|---|
| Boolean | Returns
NumberDecimal("0") for false.Returns NumberDecimal("1") for true. |
| Double | Returns double value as a decimal. |
| Decimal | No-op. Returns the decimal. |
| Integer | Returns the int value as a decimal. |
| Long | Returns the long value as a decimal. |
| String | Returns the numerical value of the string as a decimal. The string value must be of a base10 numeric value (e.g. You cannot convert a string value of a non-base10
number (e.g. |
| Date | Returns the number of milliseconds since the epoch that corresponds to the date value. |
The following table lists some conversion to decimal examples:
{$toDecimal: true} |
NumberDecimal(“1”) |
{$toDecimal: false} |
NumberDecimal(“0”) |
{$toDecimal: 2.5} |
NumberDecimal(“2.50000000000000”) |
{$toDecimal: NumberInt(5)} |
NumberDecimal(“5”) |
{$toDecimal: NumberLong(10000)} |
NumberDecimal(“10000”) |
{$toDecimal: "-5.5"} |
NumberDecimal(“-5.5”) |
{$toDecimal: ISODate("2018-03-27T05:04:47.890Z")} |
NumberDecimal(“1522127087890”) |
Create a collection orders with the following documents:
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:
The operation returns the following documents:
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use $convert instead.