On this page本页内容
$toLong¶New in version 4.0.版本4.0中的新功能。
Converts a value to a long. If the value cannot be converted to a long, $toLong errors. If the value is null or missing, $toLong returns null.
$toLong has the following syntax:语法如下所示:
The $toLong takes any valid expression.
The $toLong is a shorthand for the following $convert expression:
See also参阅
The following table lists the input types that can be converted to a decimal:
The following table lists the input types that can be converted to a long:
| Input Type | Behavior |
|---|---|
| Boolean | Returns NumberLong(0) for
false.Returns NumberLong(1) for true. |
| Double | Returns truncated value. The truncated double value must fall within the minimum and maximum value for a long. You cannot convert a double value whose truncated value is less than the minimum long value or is greater than the maximum long value. |
| Decimal | Returns truncated value. The truncated decimal value must fall within the minimum and maximum value for a long. You cannot convert a decimal value whose truncated value is less than the minimum long value or is greater than the maximum long value. |
| Integer | Returns the int value as a long. |
| Long | No-op. Returns the long value. |
| String | Returns the numerical value of the string. The string value must be of a base10 long (e.g. You cannot convert a string value of a float or decimal or non-base10 number (e.g. |
| Date | Converts the Date into the number of milliseconds since the epoch. |
The following table lists some conversion to long examples:
{ $toLong: true } |
NumberLong(“1”) |
{ $toLong: false } |
NumberLong(“0”) |
{ $toLong: 1.99999 } |
NumberLong(“1”) |
{ $toLong: NumberDecimal("5.5000") } |
NumberLong(“5”) |
{ $toLong: NumberDecimal("9223372036854775808.0") } |
Error |
{ $toLong: NumberInt(8) } |
NumberLong(8) |
{ $toLong: ISODate("2018-03-26T04:38:28.044Z") } |
NumberLong(“1522039108044”) |
{ $toLong: "-2" } |
NumberLong(“-2”) |
{ $toLong: "2.5" } |
Error |
{ $toLong: null } |
null |
Create a collection orders with the following documents:
The following aggregation operation on the orders collection converts the qty to long before sorting by the value:
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.