$convert (aggregation)
Definition
New in version 4.0.
Converts a value to a specified type.
$convert
has the following syntax:
- {
- $convert:
- {
- input: <expression>,
- to: <type expression>,
- onError: <expression>, // Optional.
- onNull: <expression> // Optional.
- }
- }
The $convert
takes a document with the following fields:
FieldDescriptioninput
The argument can be any valid expression. For more information onexpressions, see Expressions.to
The argument can be any valid expression that resolves to one of the following numericor string identifiers:
String IdentifierNumeric IdentifierNotes“double”1For more information on the conversion to double, seeConverting to a Double.“string”2For more information on the conversion to string, seeConverting to a String.“objectId”7For more information on the conversion to objectId, seeConverting to an ObjectId.“bool”8For more information on the conversion to boolean, seeConverting to a Boolean.“date”9For more information on the conversion to date, seeConverting to a Date.“int”16For more information on the conversion to integer, seeConverting to an Integer.“long”18For more information on the conversion to long, seeConverting to a Long.“decimal”19For more information on the conversion to decimal, seeConverting to a Decimal.
onError
Optional. The value to return on encountering an error duringconversion, including unsupported type conversions. Thearguments can be any valid expression.
If unspecified, the operation throws an error uponencountering an error and stops.onNull
Optional. The value to return if the input
is null or missing.The arguments can be any valid expression.
If unspecified, $convert
returns null if theinput
is null or missing.
In addition to $convert
, MongoDB provides thefollowing aggregation operators as shorthand when the default“onError” and “onNull” behavior is acceptable:
Behavior
Converting to a Boolean
The following table lists the input types that can be converted to aboolean:
Input Type | Behavior |
---|---|
Boolean | No-op. Returns the boolean value. |
Double | Returns true if not zero.Return false if zero. |
Decimal | Returns true if not zero.Return false if zero. |
Integer | Returns true if not zero.Return false if zero. |
Long | Returns true if not zero.Return false if zero. |
ObjectId | Returns true. |
String | Returns true. |
Date | Returns true. |
The following table lists some conversion to boolean examples:
Example | Results |
---|---|
| true |
| false |
| true |
| true |
| false |
| true |
| true |
| true |
| true |
| true |
| null |
See also
Converting to an Integer
The following table lists the input types that can be converted to aninteger:
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 andmaximum value for an integer.You cannot convert a double value whose truncated value is lessthan the minimum integer value or is greater than the maximuminteger value. |
Decimal | Returns truncated value.The truncated decimal value must fall within the minimum andmaximum value for an integer.You cannot convert a decimal value whose truncated value is lessthan the minimum integer value or is greater than the maximuminteger 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 valuefor an integer.You cannot convert a long value that is less than the minimuminteger 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."-5" , "123456" ) and fall within the minimum and maximumvalue for an integer.You cannot convert a string value of a float or decimal ornon-base10 number (e.g. "-5.0" , "0x6400" ) or avalue that falls outside the minimum and maximum value for aninteger. |
The following table lists some conversion to integer examples:
Example | Results |
---|---|
| 1 |
| 0 |
| 1 |
| 5 |
| Error |
| “Could not convert to type integer.” |
| 5000 |
| Error |
| -2 |
| Error |
| null |
See also
$toInt
operator.
Converting to a Decimal
The following table lists the input types that can be converted to adecimal:
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."-5.5" , "123456" ).You cannot convert a string value of a non-base10number (e.g. "0x6400" ) |
Date | Returns the number of milliseconds since the epoch thatcorresponds to the date value. |
The following table lists some conversion to decimal examples:
Example | Results |
---|---|
| NumberDecimal(“1”) |
| NumberDecimal(“0”) |
| NumberDecimal(“2.50000000000000”) |
| NumberDecimal(“5”) |
| NumberDecimal(“10000”) |
| NumberDecimal(“-5.5”) |
| NumberDecimal(“1522127087890”) |
See also
Converting to a Double
The following table lists the input types that can be converted to adouble:
Input Type | Behavior |
---|---|
Boolean | Returns NumberLong(0) for false .Returns NumberLong(1) for true . |
Double | No-op. Returns the double. |
Decimal | Returns the decimal value as a double.The decimal value must fall within the minimum andmaximum value for a double.You cannot convert a decimal value whose value is lessthan the minimum double value or is greater than the maximumdouble value. |
Integer | Returns the int value as a double. |
Long | Returns the long value as a double. |
String | Returns the numerical value of the string as a double.The string value must be of a base10 numeric value (e.g."-5.5" , "123456" ) and fall within the minimum andmaximum value for a double.You cannot convert a string value of a non-base10number (e.g. "0x6400" ) or a value that fallsoutside the minimum and maximum value for a double. |
Date | Returns the number of milliseconds since the epoch thatcorresponds to the date value. |
The following table lists some conversion to double examples:
Example | Results |
---|---|
| 1 |
| 0 |
| 2.5 |
| 5 |
| 10000 |
| -5.5 |
| 50000000000 |
| “Could not convert to type double.” |
| 1522127087890 |
See also
Converting to a Long
The following table lists the input types that can be converted to along:
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 andmaximum value for a long.You cannot convert a double value whose truncated value is lessthan the minimum long value or is greater than the maximumlong value. |
Decimal | Returns truncated value.The truncated decimal value must fall within the minimum andmaximum value for a long.You cannot convert a decimal value whose truncated value is lessthan the minimum long value or is greater than the maximumlong 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."-5" , "123456" ) and fall within the minimum and maximumvalue for a long.You cannot convert a string value of a float or decimal ornon-base10 number (e.g. "-5.0" , "0x6400" ) or avalue that falls outside the minimum and maximum valuefor a long. |
Date | Converts the Date into the number of milliseconds since theepoch. |
The following table lists some conversion to long examples:
Example | Results |
---|---|
| NumberLong(“1”) |
| NumberLong(“0”) |
| NumberLong(“1”) |
| NumberLong(“5”) |
| Error |
| “Could not convert to type long.” |
| NumberLong(8) |
| NumberLong(“1522039108044”) |
| NumberLong(“-2”) |
| Error |
| null |
See also
Converting to a Date
The following table lists the input types that can be converted to adate:
Input Type | Behavior |
---|---|
Double | Returns a date that corresponds to the number of millisecondsrepresented by the truncated double value.Positive number corresponds to the number of milliseconds sinceJan 1, 1970.Negative number corresponds to the number of milliseconds beforeJan 1, 1970. |
Decimal | Returns a date that corresponds to the number of millisecondsrepresented by the truncated decimal value.Positive number corresponds to the number of milliseconds sinceJan 1, 1970.Negative number corresponds to the number of milliseconds beforeJan 1, 1970. |
Long | Returns a date that corresponds to the number of millisecondsrepresented by the long value.Positive number corresponds to the number of milliseconds sinceJan 1, 1970.Negative number corresponds to the number of milliseconds beforeJan 1, 1970. |
String | Returns a date that corresponds to the date string.The string must be a valid date string, such as:- “2018-03-03”- “2018-03-03T12:00:00Z”- “2018-03-03T12:00:00+0500” |
ObjectId | Returns a date that corresponds to the timestamp of theObjectId. |
The following table lists some conversion to date examples:
Example | Results |
---|---|
| ISODate(“1973-10-20T21:20:00Z”) |
| ISODate(“2009-09-19T14:53:56Z”) |
| ISODate(“2004-11-09T11:33:20Z”) |
| ISODate(“1935-02-22T12:26:40Z”) |
| ISODate(“2018-03-27T04:08:58Z”) |
| ISODate(“2018-03-03T00:00:00Z”) |
| ISODate(“2018-03-20T06:00:06Z”) |
| Error |
| “Could not convert to type date.” |
See also
$toDate
operator, $dateFromString
Converting to an ObjectId
The following table lists the input types that can be converted to anObjectId:
Input Type | Behavior |
---|---|
String | Returns an ObjectId for the hexadecimal string of length 24.You cannot convert a string value that is not a hexadecimalstring of length 24. |
The following table lists some conversion to date examples:
Example | Results |
---|---|
| ObjectId(“5ab9cbfa31c2ab715d42129e”) |
| Error |
| “Could not convert to type ObjectId.” |
See also
$toObjectId
operator.
Converting to a String
The following table lists the input types that can be converted to astring:
Input Type | Behavior |
---|---|
Boolean | Returns the boolean value as a string. |
Double | Returns the double value as a string. |
Decimal | Returns the decimal value as a string. |
Integer | Returns the integer value as a string. |
Long | Returns the long value as a string. |
ObjectId | Returns the ObjectId value as a hexadecimal string.. |
String | No-op. Returns the string value. |
Date | Returns the date as a string. |
The following table lists some conversion to string examples:
Example | Results |
---|---|
| “true” |
| “false” |
| “2.5” |
| “2” |
| “1000” |
| “5ab9c3da31c2ab715d421285” |
| “2018-03-27T16:58:51.538Z” |
See also
$toString
operator. $dateToString
Example
Create a collection orders
with the following documents:
- db.orders.insert( [
- { _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" },
- { _id: 5, item: "bananas", qty: 5000000000, price: NumberDecimal("1.25") }
- ] )
The following aggregation operation on the orders
collectionconverts the price
to a decimal:
- // Define stage to add convertedPrice and convertedQty fields with the converted price and qty values
- // If price or qty values are missing, the conversion returns a value of decimal value or int value of 0.
- // If price or qty values cannot be converted, the conversion returns a string
- priceQtyConversionStage = {
- $addFields: {
- convertedPrice: { $convert: { input: "$price", to: "decimal", onError: "Error", onNull: NumberDecimal("0") } },
- convertedQty: { $convert: {
- input: "$qty", to: "int",
- onError:{$concat:["Could not convert ", {$toString:"$qty"}, " to type integer."]},
- onNull: NumberInt("0")
- } },
- }
- };
- totalPriceCalculationStage = {
- $project: { totalPrice: {
- $switch: {
- branches: [
- { case: { $eq: [ { $type: "$convertedPrice" }, "string" ] }, then: "NaN" },
- { case: { $eq: [ { $type: "$convertedQty" }, "string" ] }, then: "NaN" },
- ],
- default: { $multiply: [ "$convertedPrice", "$convertedQty" ] }
- }
- } } };
- db.orders.aggregate( [
- priceQtyConversionStage,
- totalPriceCalculationStage
- ])
The operation returns the following documents:
- { "_id" : 1, "totalPrice" : NumberDecimal("50.0000000000000") }
- { "_id" : 2, "totalPrice" : NumberDecimal("200.0") }
- { "_id" : 3, "totalPrice" : NumberDecimal("9.98") }
- { "_id" : 4, "totalPrice" : NumberDecimal("0") }
- { "_id" : 5, "totalPrice" : "NaN" }