- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $toInt (aggregation)
$toInt (aggregation)¶
On this page
Definition¶
-
$toInt¶ New in version 4.0.
Converts a value to an integer. If the value cannot be converted to an integer,
$toInterrors. If the value is null or missing,$toIntreturns null.$toInthas the following syntax:The
$toInttakes any valid expression.The
$toIntis a shorthand for the following$convertexpression:See also
Behavior¶
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:
| Example | Results |
|---|---|
$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 |
Example¶
Create a collection orders with the following documents:
The following aggregation operation:
- converts
qtyto an integer, - converts
priceto a decimal, - calculates 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.