Definition
Compatibility
You can use $convert for deployments hosted in the following environments:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
Changed in version 8.0.
{ $convert: { input: <expression>, to: <type expression> || { type: <type expression>, subtype: <int> }, format: <string>, onError: <expression>, onNull: <expression> }}The $convert takes a document with the following fields:
Field | Necessity | Description |
|---|---|---|
| Required | The argument can be any valid expression. For more information on expressions, see Expressions. |
| Required | Specifies the type to convert the
|
| Required if specifying | The argument can be any valid expression that resolves to a numeric or string identifier. For available identifiers, see Type Identifiers. |
| Optional | If |
| Required when converting to or from binData. | Specifies the binData format of the input or output. Can be one of these values:
If |
| Optional | Value to return on encountering an error during conversion, including unsupported type conversions. The arguments can be any valid expression. If unspecified, the operation throws an error upon encountering an error and stops. |
| Optional | Value to return if the If unspecified, |
In addition to $convert, MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable:
Type Identifiers
The to.type field accepts the following numeric and string identifiers:
String Identifier | Numeric Identifier | Notes |
|---|---|---|
"double" | 1 | |
"string" | 2 | |
"binData" | 5 | |
"objectId" | 7 | |
"bool" | 8 | |
"date" | 9 | See Convert to Date. |
"int" | 16 | |
"long" | 18 | See Convert to Long. |
"decimal" | 19 |
Binary Subtypes
The following table lists the valid values for the to.subtype field:
Number | Description |
|---|---|
0 | Generic binary subtype |
1 | Function data |
2 | Binary (old) |
3 | UUID (old) |
4 | UUID |
5 | MD5 |
6 | Encrypted BSON value |
7 | Compressed time series data New in version 5.2. |
8 | Sensitive data, such as a key or secret. MongoDB does not log literal values for binary data with subtype 8. Instead, MongoDB logs a placeholder value of |
9 | Vector data, which is densely packed arrays of numbers of the same type. |
128 | Custom data |
Behavior
Convert to BinData
You can only convert strings to binData. All other input types result in an error.
See the following example conversions to binData:
Example | Result |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
Note
In MongoDB 8.0, $convert returns the original value and original subtype: no conversion is performed. MongoDB versions before 8.0 don't have binData conversion.
Convert to Boolean
The following table lists the input types that can be converted to a boolean:
Input Type | Behavior |
|---|---|
Array | Returns true |
Binary data | Returns true |
Boolean | No-op. Returns the boolean value. |
Code | Returns true |
Date | Returns true |
Decimal | Returns true if not zero |
Double | Returns true if not zero |
Integer | Returns true if not zero |
JavaScript | Returns true |
Long | Returns true if not zero |
MaxKey | Returns true |
MinKey | Returns true |
Null | Returns the value specified for the |
Object | Returns true |
ObjectId | Returns true |
Regular expression | Returns true |
String | Returns true |
Timestamp | Returns true |
To learn more about data types in MongoDB, see BSON Types.
The following table lists some conversion to boolean examples:
Example | Results |
|---|---|
| true |
| false |
| true |
| true |
| false |
| true |
| true |
| true |
| true |
| true |
| null |
Tip
Convert to Integer
The following table lists the input types that can be converted to an integer:
Input Type | Behavior |
|---|---|
Boolean | Returns |
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 base 10 integer (e.g. You cannot convert a string value of a float or decimal or non-base 10 number (e.g. |
The following table lists some conversion to integer examples:
Example | Results |
|---|---|
| 1 |
| 0 |
| 1 |
| 5 |
| Error |
| 5000 |
| Error |
| -2 |
| Error |
| null |
Tip
$toInt operator.
Convert to Decimal
The following table lists the input types that can be converted to a decimal:
Input Type | Behavior |
|---|---|
Boolean | Returns |
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 base 10 numeric value (e.g. You cannot convert a string value of a non-base 10 number (e.g. |
Date | Returns the number of milliseconds since the epoch that corresponds to the date value. |
The following table lists some conversion to decimal examples:
Example | Results |
|---|---|
| Decimal128("1") |
| Decimal128("0") |
| Decimal128( "2.50000000000000" ) |
| Decimal128("5") |
| Decimal128("10000") |
| Decimal128("-5.5") |
| Decimal128("1522039108044") |
Tip
Convert to Double
The following table lists the input types that can be converted to a double:
Input Type | Behavior |
|---|---|
Boolean | Returns NumberDouble(0) for |
Double | No-op. Returns the double. |
Decimal | Returns the decimal value as a double. The decimal value must fall within the minimum and maximum value for a double. You cannot convert a decimal value whose value is less than the minimum double value or is greater than the maximum double 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 base 10 numeric value (e.g. You cannot convert a string value of a non-base 10 number (e.g. |
Date | Returns the number of milliseconds since the epoch that corresponds to the date value. |
The following table lists some conversion to double examples:
Example | Results |
|---|---|
| 1 |
| 0 |
| 2.5 |
| 5 |
| 10000 |
| -5.5 |
| 50000000000 |
| 1522039108044 |
Tip
Convert to Long
The following table lists the input types that can be converted to a long:
Input Type | Behavior |
|---|---|
Boolean | Returns |
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 base 10 long (e.g. You cannot convert a string value of a float or decimal or non-base 10 number (e.g. |
Date | Converts the Date into the number of milliseconds since the epoch. |
The following table lists some conversion to long examples:
Example | Results |
|---|---|
| Long("1") |
| Long("0") |
| Long("2") |
| Long("5") |
| Error |
| Long("8") |
| Long("1522039108044") |
| Long("-2") |
| Error |
| null |
Tip
Convert to Date
The following table lists the input types that can be converted to a date:
Input Type | Behavior |
|---|---|
Double | Returns a date that corresponds to the number of milliseconds represented by the truncated double value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
Decimal | Returns a date that corresponds to the number of milliseconds represented by the truncated decimal value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
Long | Returns a date that corresponds to the number of milliseconds represented by the long value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
String | Returns a date that corresponds to the date string. The string must be a valid date string, such as:
|
ObjectId | Returns a date that corresponds to the timestamp of the ObjectId. |
Timestamp | Returns a date that corresponds to the timestamp. |
The following table lists some conversion to date examples:
Example | Results |
|---|---|
| ISODate("1973-10-20T21:20:00.000Z") |
| ISODate("2009-09-19T14:53:56.000Z") |
| ISODate("2004-11-09T11:33:20.000Z") |
| ISODate("1935-02-22T12:26:40.000Z") |
| ISODate("2018-03-27T04:08:58.000Z") |
| ISODate("2018-03-03T00:00:00.000Z") |
| ISODate("2018-03-20T06:00:06.000Z") |
| Error |
| ISODate("2021-11-23T17:21:58.000Z") |
Tip
$toDateoperator
Convert to ObjectId
The following table lists the input types that can be converted to an ObjectId:
Input Type | Behavior |
|---|---|
String | Returns an ObjectId for the hexadecimal string of length 24. You cannot convert a string value that is not a hexadecimal string of length 24. |
The following table lists some conversion to date examples:
Example | Results |
|---|---|
| ObjectId("5ab9cbfa31c2ab715d42129e") |
| Error |
Tip
$toObjectId operator.
Convert to String
The following table lists the input types that can be converted to a string:
Input Type | Behavior |
|---|---|
BinData | Returns the binary data value as a string. |
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" |
| 'hn3f' |
| "invalid" |
Examples
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Base Conversion Example
Hexadecimal strings are a compact way to represent integers, and many systems exchange identifiers as hexadecimal values. The following example converts each movie's numeric imdb.id to a hexadecimal string:
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Toy Story", "Metropolis" ] } } }, { $sort: { title: 1 } }, { $project: { _id: 0, title: 1, imdbId: "$imdb.id", hexId: { $convert: { input: "$imdb.id", to: "string", base: 16 } } } }] )[ { title: 'Metropolis', imdbId: 293416, hexId: '47A28' }, { title: 'The Godfather', imdbId: 68646, hexId: '10C26' }, { title: 'Toy Story', imdbId: 114709, hexId: '1C015' }]To convert a hexadecimal string back to an integer, pass the string to $convert with base: 16 and to: "int".
Type Conversion Example
The following aggregation operation converts the imdb.rating field, which is a double in most documents but an empty string in others, to a double. It also converts the metacritic field, which is missing from some documents, to an integer. The $match stage selects three movies that illustrate each conversion outcome:
db.movies.aggregate( [ { $match: { title: { $in: [ "The Danish Girl", "The Godfather", "Gertie the Dinosaur" ] } } }, { $project: { _id: 0, title: 1, rating: { $convert: { input: "$imdb.rating", to: "double", onError: "Error", onNull: 0 } }, metacritic: { $convert: { input: "$metacritic", to: "int", onError: "Error", onNull: 0 } } } }, { $sort: { title: 1 } }] )[ { title: 'Gertie the Dinosaur', rating: 7.3, metacritic: 0 }, { title: 'The Danish Girl', rating: 'Error', metacritic: 0 }, { title: 'The Godfather', rating: 9.2, metacritic: 100 }]For The Danish Girl, the empty string in imdb.rating cannot convert to a double, so onError returns "Error". For Gertie the Dinosaur and The Danish Girl, metacritic is missing, so onNull returns 0.