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.3.
{ $convert: { input: <expression>, to: <type expression> || { type: <type expression>, subtype: <int> }, base: <expression>, // new in 8.3 format: <string>, onError: <expression>, onNull: <expression> } }
$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. Starting in MongoDB 8.1, you can set the
Starting in MongoDB 8.3, you can also set the MongoDB also supports these numeric types as input when converting a value
to | ||||||||||||||||||||||||||||||||||||
| Required | Specifies the type to convert the
| ||||||||||||||||||||||||||||||||||||
| Required if specifying | The argument can be any valid expression that resolves to one of the following numeric or string identifiers:
| ||||||||||||||||||||||||||||||||||||
| Optional | If
Default: 0 (Generic binary subtype) | ||||||||||||||||||||||||||||||||||||
| Optional | Specifies big or little endian byte ordering for conversions between | ||||||||||||||||||||||||||||||||||||
| Optional | Integer base for conversions between string and numeric types.
New in version 8.3. | ||||||||||||||||||||||||||||||||||||
| Required when converting to or from | Specifies format of conversions between
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:
Behavior
The following sections describe how to convert values to different types.
Convert to BinData
Starting in MongoDB 8.1, you can set the to field to binData if
you set the input field to one of the following types:
intlongdouble
Starting in MongoDB 8.1, $convert returns an error when attempting
to convert between different binData subtypes. 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 from numeric types to binData:
When converting a numeric type to binData:
An
intbecomes a 4-bytebinData.A
longbecomes an 8-bytebinData.A
doublebecomes an 8-bytebinData.
The byteOrder of the numeric output defaults to "little", or the placement of
the least significant byte first. In contrast, "big" places the most significant
byte first.
Convert long to binData:
Input:
db.t.insertOne( { a: Long(42) } )
db.t.aggregate([ { $project: { _id: 0, convertedBD: { $convert: { input: "$a", to: "binData", } }, } } ])
Output:
[ { convertedBD: Binary.createFromBase64('KgAAAAAAAAA=', 0) } ]
Convert long to binData with big-endian byte ordering:
Input:
db.t.insertOne( { a: Long(42) } )
db.t.aggregate([ { $project: { _id: 0, convertedBD: { $convert: { input: "$a", to: "binData", byteOrder: "big", } }, } } ])
Output:
[ { convertedBD: Binary.createFromBase64('AAAAAAAAACo=', 0), } ]
Convert double to binData:
Input:
db.t.insertOne( { a: Double(42.0) } )
db.t.aggregate([ { $project: { _id: 0, convertedBD: { $convert: { input: "$a", to: "binData", } }, } } ])
Output:
[ { convertedBD: Binary.createFromBase64('AAAAAAAARUA=', 0) } ]
Convert int to binData:
Input:
db.t.insertOne( { a: 42 } )
db.t.aggregate([ { $project: { _id: 0, convertedBD: { $convert: { input: "$a", to: "binData", } }, } } ])
Output:
[ { convertedBD: Binary.createFromBase64('KgAAAA==', 0) } ]
Convert an array of numeric values to binData:
This example shows how $convert converts arrays containing different types
of numeric values into binData.
Input:
db.t.insertMany([ // Empty array { a: [ ] }, // Bool array { a: [ false, true, true, true, true, true, true, true, false, false, false, false, false, true, true, true ] }, // Int array { a: [NumberInt(0), NumberInt(1), NumberInt(0), NumberInt(10)] }, // Double array { a: [ Double(0.0), Double(1.0), Double(0.0), Double(1.0), Double(3.14) ] }, ])
db.t.aggregate([ { $project: { _id: 0, original: "$a", convertedVector: { $convert: { input: "$a", to: { type: "binData" } } } } } ])
Output:
[ { original: [], convertedVector: Binary.fromPackedBits(new Uint8Array([])) }, { original: [ false, true, true, true, true, true, true, true, false, false, false, false, false, true, true, true ], convertedVector: Binary.fromPackedBits(new Uint8Array([ 127, 7 ])) }, { original: [ 0, 1, 0, 10 ], convertedVector: Binary.fromInt8Array(new Int8Array([ 0, 1, 0, 10 ])) }, { original: [ 0, 1, 0, 1, 3.14 ], convertedVector: Binary.fromFloat32Array(new Float32Array([ 0, 1, 0, 1, 3.140000104904175 ])) } ]
Convert from string to BinData
MongoDB also supports conversions between binData and strings.
The following examples demonstrate how to convert strings to binData.
Example | Result | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| | |||||||||||
| | |||||||||||
| | |||||||||||
| | |||||||||||
| | |||||||||||
| | |||||||||||
| |
Note
Starting in MongoDB 8.1, $convert returns an error when attempting
to convert between different binData subtypes. 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 Array
New in version 8.3.
The following table lists the input types that can be converted to an array:
Input Type | Behavior |
|---|---|
binData | Returns an array of numeric values. The numeric type of the array elements depends on the binData format. |
String | Returns an array corresponding to the content within the string. The string must contain characters that represent a valid JSON array. |
Null or Missing | Returns null. |
The following table lists some conversion of string to array examples:
Example | Results | ||
|---|---|---|---|
| [ 1, 2, 3 ] | ||
| [ 'a', 'b', 'c' ] | ||
| [ ] | ||
| Error: Input doesn't match expected type 'array' | ||
| Error: Unsupported conversion from int to array in $convert with no onError value | ||
| Error: Input doesn't represent valid JSON: Unexpected standalone value | ||
| [ { '$oid': '507f1f77bcf86cd799439011' } ] | ||
| [ 1, 2, 3 ] NoteThe | ||
| 'on error!' | ||
| 'on null!' |
Convert binData to Array
This example shows how $convert converts binData of different formats
into arrays containing values of their respective types:
Input:
db.t.insertMany([ // Empty PACKED_BIT vector converts to empty array { v: BinData(9, "EAA=") }, // PACKED_BIT vector converts to bool array { v: BinData(9, "EAB/Bw==") }, // INT8 vector converts to int array { v: BinData(9, "AwAAAQ==") }, // FLOAT32 vector converts to double array { v: BinData(9, "JwCamZk+") }, // FLOAT32 vector with special values converts to [-Infinity, 0, Infinity] { v: BinData(9, "JwAAAID/AAAAAAAAgH8=") } ])
db.t.aggregate([ { $project: { _id: 0, original: "$v", asArray: { $convert: { input: "$v", to: { type: "array" } } } } } ])
Output:
[ { original: Binary.fromPackedBits(new Uint8Array([])), asArray: [] }, { original: Binary.fromPackedBits(new Uint8Array([ 127, 7 ])), asArray: [ false, true, true, true, true, true, true, true, false, false, false, false, false, true, true, true ] }, { original: Binary.fromInt8Array(new Int8Array([ 0, 1 ])), asArray: [ 0, 1 ] }, { original: Binary.fromFloat32Array(new Float32Array([ 0.30000001192092896 ])), asArray: [ 0.30000001192092896 ] }, { original: Binary.fromFloat32Array(new Float32Array([ -Infinity, 0, Infinity ])), asArray: [ -Infinity, 0, Infinity ] } ]
Convert to Object
New in version 8.3.
The following table lists the input types that can be converted to an object:
Input Type | Behavior |
|---|---|
String | Returns a document corresponding to the content within the string. The string must contain characters that represent a valid JSON object. |
Null or Missing | Returns null. |
The following table lists some conversion to object examples:
Example | Results | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| { a: 1, b: 2 } | ||||||||
| { } | ||||||||
| Error: Input doesn't match expected type 'object' | ||||||||
| Error: Input doesn't represent valid JSON: Unexpected standalone value | ||||||||
| Error: Input doesn't represent valid JSON: Illegal embedded null byte | ||||||||
| { name: 'fox00o' } | ||||||||
| { a: 3, b: 2 } | ||||||||
| { foo: null } | ||||||||
| { foo: false } | ||||||||
| { ['__proto__']: { foo: null } } | ||||||||
| { foo: 'NaN' } | ||||||||
| { foo: 123 } | ||||||||
| { foo: Long('4294967296') } | ||||||||
| { foo: 1.123123 } | ||||||||
| { foo: 1200 } | ||||||||
| { largePos: 18446744073709552000 } | ||||||||
| { largeNeg: -18446744073709552000 } | ||||||||
| null | ||||||||
| { objectId: '507f1f77bcf86cd799439011', uuid: '3b241101-e2bb-4255-8caf-4136c566a962', date: '2018-03-27T16:58:51.538Z', regex: '/^ABC/i', js: 'function (s) {return s + "foo";}', timestamp: 'Timestamp(1565545664, 1)', arr: [ 1, 2, 3 ] } |
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 Return false if zero |
Double | Returns true if not zero Return false if zero |
Integer | Returns true if not zero Return false if zero |
JavaScript | Returns true |
Long | Returns true if not zero Return false if 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 |
Convert to Integer
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. |
BinData | Returns the The number of bytes in the If the |
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. If you omit If you specify |
The following table lists some conversion to integer examples:
Example | Results | |||||
|---|---|---|---|---|---|---|
| 1 | |||||
| 0 | |||||
| 1 | |||||
| 5 | |||||
| Error | |||||
| 5000 | |||||
| Error | |||||
| -2 | |||||
| Error | |||||
| null | |||||
| 1048576 | |||||
| -1763180545 | |||||
| Error: Failed to convert BinData because of invalid length: 7 |
Convert to Decimal
The following table lists the input types that can be converted to a decimal:
Input Type | Behavior |
|---|---|
Boolean | Returns Decimal128( "0" ) for false.Returns Decimal128( "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. If you omit If you specify |
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") |
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 false.Returns NumberDouble(1) for true. |
BinData | Returns the The number of bytes in the If the |
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. If you omit If you specify |
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 | |||||
| 4.814824932714571e-36 | |||||
| Error: Failed to convert binData because of invalid length: 2 |
Subnormal Numbers
Starting in MongoDB 8.3, the server is able to parse the full range of all representable double precision floating point numbers. This includes subnormal numbers where the most significant digit has leading zeroes and the exponent has the least possible value. For details, see Subnormal Number.
In earlier versions of MongoDB, the server returns an error when you try to parse these numbers. The following example raises an error in versions earlier than MongoDB 8.3:
db.t.insertOne( { v: "7.08263e-317" } ) db.t.aggregate([ { $project: { converted: { $convert: { input: "$v", to: "double" }, } } } ])
This example fails with an error similar to the following:
MongoServerError[ConversionFailure]: Executor error during aggregate command on namespace: test.t :: caused by :: Failed to parse number '7.08263e-317' in $convert with no onError value: Out of range
Convert to Long
The following table lists the input types that can be converted to a long:
Input Type | Behavior |
|---|---|
Boolean | Returns 0 for false.Returns 1 for true. |
BinData | Returns the The number of bytes in the If the |
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. If you omit If you specify |
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 | |||||
| Long("1048576") |
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") |
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 |
Convert to String
The following table lists the input types that can be converted to a string:
Input Type | Behavior |
|---|---|
Array | Returns the New in version 8.3. |
BinData | If the |
Boolean | Returns the Boolean value as a string. |
Date | Returns the |
Decimal | Returns the |
Double | Returns the |
Integer | Returns the |
Long | Returns the |
MaxKey | Returns the New in version 8.3. |
MinKey | Returns the New in version 8.3. |
Object | Returns the object as a string. New in version 8.3. |
ObjectId | Returns the |
Regular Expression | Returns the New in version 8.3. |
String | No operation. Returns the string value. |
Timestamp | Returns the New in version 8.3. |
Note
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
Base Conversion Example
Create a collection examples with a placeholder document:
db.examples.insertOne({ _id: 1 })
The following example converts between numbers and strings using different bases:
db.examples.aggregate([ { $project: { _id: 0, bin: { $convert: { input: 10, to: "string", base: 2 } }, hex: { $convert: { input: 10, to: "string", base: 16 } }, intFromBin: { $convert: { input: "1010", to: "int", base: 2 } }, intFromHex: { $convert: { input: "A", to: "int", base: 16 } } } } ])
This operation returns the following document:
{ bin: "1010", hex: "A", intFromBin: 10, intFromHex: 10 }
Type Conversion Example
Create a collection orders with the following documents:
db.orders.insertMany( [ { _id: 1, item: "apple", qty: 5, price: 10 }, { _id: 2, item: "pie", qty: 10, price: Decimal128("20.0") }, { _id: 3, item: "ice cream", qty: 2, price: "4.99" }, { _id: 4, item: "almonds" }, { _id: 5, item: "bananas", qty: 5000000000, price: Decimal128("1.25") } ] )
The following aggregation operation on the orders collection
converts 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: Decimal128("0") } }, convertedQty: { $convert: { input: "$qty", to: "int", onError:{ $concat: [ "Could not convert ", { $toString:"$qty" }, " to type integer." ] }, onNull: Int32("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: Decimal128("50") }, { _id: 2, totalPrice: Decimal128("200.0") }, { _id: 3, totalPrice: Decimal128("9.98") }, { _id: 4, totalPrice: Decimal128("0") }, { _id: 5, totalPrice: 'NaN' }
Learn More
Convert a value to an array with
$toArrayConvert a string to an object with
$toObjectConvert a value to a boolean with
$toBoolConvert a value to an integer with
$toIntConvert a value to a decimal with
$toDecimalConvert a value to a double with
$toDoubleConvert a value to a long with
$toLongConvert a value to a date with
$toDateConvert a value to an ObjectId with
$toObjectIdConvert a value to a string with
$toStringConvert a date string to a date object with
$dateFromStringConvert a date object to a string with
$dateToString