$convert (aggregation)

Definition

  • $convert

New in version 4.0.

Converts a value to a specified type.

$convert has the following syntax:

  1. {
  2. $convert:
  3. {
  4. input: <expression>,
  5. to: <type expression>,
  6. onError: <expression>, // Optional.
  7. onNull: <expression> // Optional.
  8. }
  9. }

The $convert takes a document with the following fields:

FieldDescriptioninputThe argument can be any valid expression. For more information onexpressions, see Expressions.toThe 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.

onErrorOptional. 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.onNullOptional. 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 TypeBehavior
BooleanNo-op. Returns the boolean value.
DoubleReturns true if not zero.Return false if zero.
DecimalReturns true if not zero.Return false if zero.
IntegerReturns true if not zero.Return false if zero.
LongReturns true if not zero.Return false if zero.
ObjectIdReturns true.
StringReturns true.
DateReturns true.

The following table lists some conversion to boolean examples:

ExampleResults
  1. { input: true, to: "bool"}
true
  1. { input: false, to: "bool" }
false
  1. { input: 1.99999, to: "bool" }
true
  1. { input: NumberDecimal("5"), to: "bool"}
true
  1. { input: NumberDecimal("0"), to: "bool"}
false
  1. { input: 100, to: "bool" }
true
  1. { input: ISODate("2018-03-26T04:38:28.044Z"), to: "bool" }
true
  1. { input: "hello", to: "bool" }
true
  1. { input: "false", to: "bool" }
true
  1. { input: "", to: "bool" }
true
  1. { input: null, to: "bool" }
null

See also

$toBool

Converting to an Integer

The following table lists the input types that can be converted to aninteger:

Input TypeBehavior
BooleanReturns 0 for false.Returns 1 for true.
DoubleReturns 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.
DecimalReturns 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.
IntegerNo-op. Returns the integer value.
LongReturns 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.
StringReturns 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:

ExampleResults
  1. { input: true, to: "int"}
1
  1. { input: false, to: "int" }
0
  1. { input: 1.99999, to: "int" }
1
  1. { input: NumberDecimal("5.5000"), to: "int"}
5
  1. { input: NumberDecimal("9223372036000.000"), to: "int"}
Error
  1. { input: NumberDecimal("9223372036000.000"), to: "int", onError: "Could not convert to type integer."}
“Could not convert to type integer.”
  1. { input: NumberLong("5000"), to: "int"}
5000
  1. { input: NumberLong("922337203600"), to: "int"}
Error
  1. { input: "-2", to: "int" }
-2
  1. { input: "2.5", to: "int" }
Error
  1. { input: null, to: "int" }
null

See also

$toInt operator.

Converting to a Decimal

The following table lists the input types that can be converted to adecimal:

Input TypeBehavior
BooleanReturns NumberDecimal("0") for false.Returns NumberDecimal("1") for true.
DoubleReturns double value as a decimal.
DecimalNo-op. Returns the decimal.
IntegerReturns the int value as a decimal.
LongReturns the long value as a decimal.
StringReturns 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")
DateReturns the number of milliseconds since the epoch thatcorresponds to the date value.

The following table lists some conversion to decimal examples:

ExampleResults
  1. { input: true, to: "decimal"}
NumberDecimal(“1”)
  1. { input: false, to: "decimal" }
NumberDecimal(“0”)
  1. { input: 2.5, to: "decimal" }
NumberDecimal(“2.50000000000000”)
  1. { input: NumberInt(5), to: "decimal"}
NumberDecimal(“5”)
  1. { input: NumberLong(10000), to: "decimal"}
NumberDecimal(“10000”)
  1. { input: "-5.5", to: "decimal" }
NumberDecimal(“-5.5”)
  1. { input: ISODate("2018-03-27T05:04:47.890Z"), to: "decimal" }
NumberDecimal(“1522127087890”)

See also

$toDecimal

Converting to a Double

The following table lists the input types that can be converted to adouble:

Input TypeBehavior
BooleanReturns NumberLong(0) for false.Returns NumberLong(1) for true.
DoubleNo-op. Returns the double.
DecimalReturns 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.
IntegerReturns the int value as a double.
LongReturns the long value as a double.
StringReturns 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.
DateReturns the number of milliseconds since the epoch thatcorresponds to the date value.

The following table lists some conversion to double examples:

ExampleResults
  1. { input: true, to: "double"}
1
  1. { input: false, to: "double" }
0
  1. { input: 2.5, to: "double" }
2.5
  1. { input: NumberInt(5), to: "double"}
5
  1. { input: NumberLong(10000), to: "double"}
10000
  1. { input: "-5.5", to: "double" }
-5.5
  1. { input: "5e10", to: "double" }
50000000000
  1. { input: "5e550", to: "double", onError: "Could not convert to type double."}
“Could not convert to type double.”
  1. { input: ISODate("2018-03-27T05:04:47.890Z"), to: "double" }
1522127087890

See also

$toDouble

Converting to a Long

The following table lists the input types that can be converted to along:

Input TypeBehavior
BooleanReturns 0 for false.Returns 1 for true.
DoubleReturns 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.
DecimalReturns 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.
IntegerReturns the int value as a long.
LongNo-op. Returns the long value.
StringReturns 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.
DateConverts the Date into the number of milliseconds since theepoch.

The following table lists some conversion to long examples:

ExampleResults
  1. { input: true, to: "long" }
NumberLong(“1”)
  1. { input: false, to: "long" }
NumberLong(“0”)
  1. { input: 1.99999, to: "long" }
NumberLong(“1”)
  1. { input: NumberDecimal("5.5000"), to: "long" }
NumberLong(“5”)
  1. { input: NumberDecimal("9223372036854775808.0"), to: "long" }
Error
  1. { input: NumberDecimal("9223372036854775808.000"), to: "long", onError: "Could not convert to type long."}
“Could not convert to type long.”
  1. { input: NumberInt(8), to: "long" }
NumberLong(8)
  1. { input: ISODate("2018-03-26T04:38:28.044Z"), to: "long" }
NumberLong(“1522039108044”)
  1. { input: "-2", to: "long" }
NumberLong(“-2”)
  1. { input: "2.5", to: "long" }
Error
  1. { input: null, to: "long" }
null

See also

$toLong

Converting to a Date

The following table lists the input types that can be converted to adate:

Input TypeBehavior
DoubleReturns 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.
DecimalReturns 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.
LongReturns 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.
StringReturns 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”
ObjectIdReturns a date that corresponds to the timestamp of theObjectId.

The following table lists some conversion to date examples:

ExampleResults
  1. { input: 120000000000.5, to: "date"}
ISODate(“1973-10-20T21:20:00Z”)
  1. { input: NumberDecimal("1253372036000.50"), to: "date"}
ISODate(“2009-09-19T14:53:56Z”)
  1. { input: NumberLong("1100000000000"), to: "date"}
ISODate(“2004-11-09T11:33:20Z”)
  1. { input: NumberLong("-1100000000000"), to: "date"}
ISODate(“1935-02-22T12:26:40Z”)
  1. { input: ObjectId("5ab9c3da31c2ab715d421285"), to: "date" }
ISODate(“2018-03-27T04:08:58Z”)
  1. { input: "2018-03-03", to: "date" }
ISODate(“2018-03-03T00:00:00Z”)
  1. { input: "2018-03-20 11:00:06 +0500", to: "date" }
ISODate(“2018-03-20T06:00:06Z”)
  1. { input: "Friday", to: "date" }
Error
  1. { input: "Friday", to: "date", onError: "Could not convert to type date."}
“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 TypeBehavior
StringReturns 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:

ExampleResults
  1. { input: "5ab9cbfa31c2ab715d42129e", to: "objectid"}
ObjectId(“5ab9cbfa31c2ab715d42129e”)
  1. { input: "5ab9cbfa31c2ab715d42129", to: "objectid"}
Error
  1. { input: "5ab9cbfa31c2ab715d42129", to: "objectid", onError: "Could not convert to type ObjectId."}
“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 TypeBehavior
BooleanReturns the boolean value as a string.
DoubleReturns the double value as a string.
DecimalReturns the decimal value as a string.
IntegerReturns the integer value as a string.
LongReturns the long value as a string.
ObjectIdReturns the ObjectId value as a hexadecimal string..
StringNo-op. Returns the string value.
DateReturns the date as a string.

The following table lists some conversion to string examples:

ExampleResults
  1. { input: true, to: "string" }
“true”
  1. { input: false, to: "string" }
“false”
  1. { input: 2.5, to: "string"}
“2.5”
  1. { input: NumberInt(2), to: "string"}
“2”
  1. { input: NumberLong(1000), to: "string"}
“1000”
  1. { input: ObjectId("5ab9c3da31c2ab715d421285"), to: "string" }
“5ab9c3da31c2ab715d421285”
  1. { input: ISODate("2018-03-27T16:58:51.538Z"), to: "string" }
“2018-03-27T16:58:51.538Z”

See also

$toString operator. $dateToString

Example

Create a collection orders with the following documents:

  1. db.orders.insert( [
  2. { _id: 1, item: "apple", qty: 5, price: 10 },
  3. { _id: 2, item: "pie", qty: 10, price: NumberDecimal("20.0") },
  4. { _id: 3, item: "ice cream", qty: 2, price: "4.99" },
  5. { _id: 4, item: "almonds" },
  6. { _id: 5, item: "bananas", qty: 5000000000, price: NumberDecimal("1.25") }
  7. ] )

The following aggregation operation on the orders collectionconverts the price to a decimal:

  1. // Define stage to add convertedPrice and convertedQty fields with the converted price and qty values
  2. // If price or qty values are missing, the conversion returns a value of decimal value or int value of 0.
  3. // If price or qty values cannot be converted, the conversion returns a string
  4.  
  5. priceQtyConversionStage = {
  6. $addFields: {
  7. convertedPrice: { $convert: { input: "$price", to: "decimal", onError: "Error", onNull: NumberDecimal("0") } },
  8. convertedQty: { $convert: {
  9. input: "$qty", to: "int",
  10. onError:{$concat:["Could not convert ", {$toString:"$qty"}, " to type integer."]},
  11. onNull: NumberInt("0")
  12. } },
  13. }
  14. };
  15.  
  16. totalPriceCalculationStage = {
  17. $project: { totalPrice: {
  18. $switch: {
  19. branches: [
  20. { case: { $eq: [ { $type: "$convertedPrice" }, "string" ] }, then: "NaN" },
  21. { case: { $eq: [ { $type: "$convertedQty" }, "string" ] }, then: "NaN" },
  22. ],
  23. default: { $multiply: [ "$convertedPrice", "$convertedQty" ] }
  24. }
  25. } } };
  26.  
  27. db.orders.aggregate( [
  28. priceQtyConversionStage,
  29. totalPriceCalculationStage
  30. ])

The operation returns the following documents:

  1. { "_id" : 1, "totalPrice" : NumberDecimal("50.0000000000000") }
  2. { "_id" : 2, "totalPrice" : NumberDecimal("200.0") }
  3. { "_id" : 3, "totalPrice" : NumberDecimal("9.98") }
  4. { "_id" : 4, "totalPrice" : NumberDecimal("0") }
  5. { "_id" : 5, "totalPrice" : "NaN" }