On this page本页内容
$toInt
¶New in version 4.0.版本4.0中的新功能。
Converts a value to an integer. If the value cannot be converted to an integer, $toInt
errors. If the value is null or missing, $toInt
returns null.
$toInt
has the following syntax:语法如下所示:
The $toInt
takes any valid expression.
The $toInt
is a shorthand for the following $convert
expression:
See also参阅
The following table lists the input types that can be converted to an integer:
Input Type | Behavior |
---|---|
Boolean | Returns
0 for false .Returns 1 for true . |
Double | Returns truncated value. The truncated double value must fall within the minimum and maximum value for an integer. You cannot convert a double value whose truncated value is less than the minimum integer value or is greater than the maximum integer value. |
Decimal | Returns truncated value. The truncated decimal value must fall within the minimum and maximum value for an integer. You cannot convert a decimal value whose truncated value is less than the minimum integer value or is greater than the maximum integer value. |
Integer | No-op. Returns the integer value. |
Long | Returns the long value as an integer. The long value must fall within the minimum and maximum value for an integer. You cannot convert a long value that is less than the minimum integer value or is greater than the maximum integer value. |
String | Returns the numerical value of the string as an integer. The string value must be a base10 integer; e.g. You cannot convert a string value of a float or decimal or non-base10 number (e.g. |
The following table lists some conversion to integer examples:
$toInt: true |
1 |
$toInt: false |
0 |
$toInt: 1.99999 |
1 |
$toInt: NumberDecimal("5.5000") |
5 |
$toInt: NumberDecimal("9223372036000.000") |
Error |
$toInt: NumberLong("5000") |
5000 |
$toInt: NumberLong("922337203600") |
Error |
$toInt: "-2" |
-2 |
$toInt: "2.5" |
Error |
$toInt: null |
null |
Create a collection orders
with the following documents:
The following aggregation operation on the orders
collection converts the qty
to an integer as well as convert price
to a decimal 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.