> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# $convert (expression operator)

## Definition

Converts a value to a specified type.

## Compatibility

You can use `$convert` for deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

* [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

* [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

**Changed in version 8.3**

```javascript
{
   $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 |
| --- | --- | --- |
| `input` | Required | The argument can be any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions). For more information on expressions, see [Expressions.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) 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: `int`; `long`; `double` Starting in MongoDB 8.3, you can also set the `to` field to `binData` if the `input` field is an `array` of numeric values. For examples, see [Convert an Array of Numeric Values to binData.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-array-of-numeric-values-to-bindata) MongoDB also supports these numeric types as input when converting a value to `binData`. Starting in MongoDB 9.0, if the `input` field resolves to an object, you can set the `to` field to `binData`. For examples, see [Convert an Object to binData.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-object-to-bindata) |
| `to` | Required | Specifies the type to convert the `input` expression to. You can set `to` to one of these values: A string or numeric identifier for the target type. See `to.type`.; An object containing the fields `to.type` and `to.subtype`. Use this format to convert to `binData` and specify a `binData` subtype. |
| `to.type` | Required if specifying `to` as an object | The argument can be any valid [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) that resolves to a numeric or string identifier. For available identifiers, see [Type Identifiers.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-type-identifiers) |
| `to.subtype` | Optional | If `to.type` is `binData`, `to.subtype` specifies the binData subtype to convert to. For valid values, see [Binary Subtypes](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-binary-subtypes). *Default:* 0 (Generic binary subtype). |
| `byteOrder` | Optional | Specifies big or little endian byte ordering for conversions between `binData` and numeric types. If unspecified, the default is little endian byte ordering. |
| `base` | Optional | Integer base for conversions between string and numeric types. If `null`, [`$convert`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#mongodb-expression-exp.-convert) behaves as if you omitted base.; If specified, MongoDB interprets the value in the chosen base when converting between strings and the numeric types `int`, `long`, `double`, and `decimal`. For other conversions, MongoDB validates the value of `base` but otherwise ignores it.; Base must be `2`, `8`, `10`, or `16`. **New in version 8.3** |
| `format` | Required when converting to or from `binData` and string | Specifies format of conversions between `binData` and string `base64`; `base64url`; `utf8`; `hex`; `uuid` If `format` is `uuid`, `to.subtype` must be `4`. |
| `onError` | Optional | Value to return on encountering an error during conversion, including unsupported type conversions. The arguments can be any valid [expression.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) If unspecified, the operation throws an error upon encountering an error and stops. |
| `onNull` | Optional | Value to return if the `input` is null or missing. The arguments can be any valid [expression.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) If unspecified, [`$convert`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#mongodb-expression-exp.-convert) returns null if the `input` is null or missing. |

In addition to [`$convert`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#mongodb-expression-exp.-convert), MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable:

- [`$toArray`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toarray.md#mongodb-expression-exp.-toArray)

- [`$toBool`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tobool.md#mongodb-expression-exp.-toBool)

- [`$toDate`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todate.md#mongodb-expression-exp.-toDate)

- [`$toDecimal`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todecimal.md#mongodb-expression-exp.-toDecimal)

- [`$toDouble`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todouble.md#mongodb-expression-exp.-toDouble)

- [`$toInt`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toint.md#mongodb-expression-exp.-toInt)

- [`$toLong`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tolong.md#mongodb-expression-exp.-toLong)

- [`$toObject`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toobject.md#mongodb-expression-exp.-toObject)

- [`$toObjectId`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toobjectid.md#mongodb-expression-exp.-toObjectId)

- [`$toString`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tostring.md#mongodb-expression-exp.-toString)

- [`$toUUID`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/touuid.md#mongodb-expression-exp.-toUUID)

### Type Identifiers

The `to.type` field accepts the following numeric and string identifiers:

| String Identifier | Numeric Identifier | Notes |
| --- | --- | --- |
| "double" | 1 | See [Convert to Double.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-double) |
| "string" | 2 | See [Convert to String.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-string) |
| "object" | 3 | See [Convert to Object.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-object) |
| "array" | 4 | See [Convert to Array.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-array) |
| "binData" | 5 | See [Convert to BinData.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-binData) |
| "objectId" | 7 | See [Convert to ObjectId.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-objectId) |
| "bool" | 8 | See [Convert to Boolean.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-bool) |
| "date" | 9 | See [Convert to Date.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-date) |
| "int" | 16 | See [Convert to Integer.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-int) |
| "long" | 18 | See [Convert to Long.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-long) |
| "decimal" | 19 | See [Convert to Decimal.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#std-label-convert-to-decimal) |

### 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

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:

- `int`

- `long`

- `double`

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 `int` becomes a 4-byte `binData`.

- A `long` becomes an 8-byte `binData`.

- A `double` becomes an 8-byte `binData`.

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:**

```javascript
db.t.insertOne( { a: Long(42) } )

```

```javascript
db.t.aggregate([
  {
    $project: {
      _id: 0,
      convertedBD: {
        $convert: {
           input: "$a",
           to: "binData",
      }
    },
  }
}
])

```

**Output**:

```javascript
[
  {
    convertedBD: Binary.createFromBase64('KgAAAAAAAAA=', 0)
  }
]

```

Convert `long` to `binData` with big-endian byte ordering:

**Input:**

```javascript
db.t.insertOne( { a: Long(42) } )

```

```javascript
db.t.aggregate([
  {
    $project: {
      _id: 0,
      convertedBD: {
        $convert: {
           input: "$a",
           to: "binData",
           byteOrder: "big",
        }
      },
    }
  }
])

```

**Output**:

```javascript
[
  {
    convertedBD: Binary.createFromBase64('AAAAAAAAACo=', 0),
  }
]

```

Convert `double` to `binData`:

**Input:**

```javascript
db.t.insertOne( { a: Double(42.0) } )

```

```javascript
db.t.aggregate([
  {
    $project: {
      _id: 0,
      convertedBD: {
        $convert: {
           input: "$a",
           to: "binData",
        }
      },
    }
  }
])

```

**Output**:

```javascript
[
  {
    convertedBD: Binary.createFromBase64('AAAAAAAARUA=', 0)
  }
]

```

Convert `int` to `binData`:

**Input:**

```javascript
db.t.insertOne( { a: 42 } )

```

```javascript
db.t.aggregate([
  {
    $project: {
      _id: 0,
      convertedBD: {
        $convert: {
           input: "$a",
           to: "binData",
        }
      },
    }
  }
])

```

**Output**:

```javascript
[
  {
    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:**

```javascript
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) ] },
])

```

```javascript
db.t.aggregate([
    {
      $project: {
        _id: 0,
        original: "$a",
        convertedVector: {
          $convert: {
            input: "$a",
            to: { type: "binData" } 
          }
        }
      }
    }
])

```

**Output**:

```javascript
[
  {
    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 an object to `binData`

**New in version 9.0**

When the `input` field resolves to an object and the `to` field is `binData`, `$convert` returns the raw BSON representation of the object. The subtype of the returned `binData` value is `0` unless you specify a different value in `to.subtype`.

Because the output is the raw BSON of the object, the order of the object's fields and the order of elements in its arrays both affect the returned bytes.

`$convert` validates the `format`, `byteOrder`, and `base` fields for this conversion, but these fields have no effect on the output.

The following table shows object to `binData` conversion examples:

| Example | Results |
| --- | --- |
| `{ input: {}, to: "binData" }` | `Binary.createFromBase64('BQAAAAA=', 0)` |
| `{
   input: {
      a: "hello",
      b: { x: NumberInt(42), y: [NumberInt(1), NumberInt(2), NumberInt(3)] },
      c: BinData(0, "AQIDBA==")
   },
   to: "binData"
}` | `Binary.createFromBase64('SgAAAAJhAAYAAABoZWxsbwADYgApAAAAEHgAKgAAAAR5ABoAAAAQMAABAAAAEDEAAgAAABAyAAMAAAAAAAVjAAQAAAAAAQIDBAA=', 0)` |
| `{ input: { a: "a", b: "b" }, to: "binData" }` | `Binary.createFromBase64('FwAAAAJhAAIAAABhAAJiAAIAAABiAAA=', 0)` |
| `{ input: { b: "b", a: "a" }, to: "binData" }` | `Binary.createFromBase64('FwAAAAJiAAIAAABiAAJhAAIAAABhAAA=', 0)` The output differs from the preceding example because the field order differs. |
| `{ input: { a: [ NumberInt(1), NumberInt(2) ] }, to: "binData" }` | `Binary.createFromBase64('GwAAAARhABMAAAAQMAABAAAAEDEAAgAAAAAA', 0)` |
| `{ input: { a: [ NumberInt(2), NumberInt(1) ] }, to: "binData" }` | `Binary.createFromBase64('GwAAAARhABMAAAAQMAACAAAAEDEAAQAAAAAA', 0)` The output differs from the preceding example because the array element order differs. |
| `{ input: { a: "a" }, to: { type: 5, subtype: 128 } }` | `Binary.createFromBase64('DgAAAAJhAAIAAABhAAA=', 128)` |
| `{ input: { a: "a" }, to: "binData", format: "hex" }` | `Binary.createFromBase64('DgAAAAJhAAIAAABhAAA=', 0)` `$convert` ignores the `format` field. |
| `{ input: { a: "a" }, to: "binData", format: "bson" }` | Error: Invalid 'format' argument for $convert: bson `$convert` validates the `format` field before ignoring it. |
| `{ input: null, to: "binData" }` | null |

#### 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 |
| --- | --- |
| `{
   input: "hn3uUsMxSE6S0cVkebjmfg==",
   to: {
      type: "binData",
      subtype: 0
   },
   format: "base64"
}` | `Binary.createFromBase64('hn3uUsMxSE6S0cVkebjmfg==', 0)` |
| `{
   input: "hn3uUsMxSE6S0cVkebjmfg==",
   to: "binData",
   format: "base64"
}` | `Binary.createFromBase64('hn3uUsMxSE6S0cVkebjmfg==', 0)` |
| `{
   input: "867dee52-c331-484e-92d1-c56479b8e67e",
   to: {
      type: "binData",
      subtype: 0
   },
   format: "base64"
}` | `Failed to parse BinData '867dee52-c331-484e-92d1-c56479b8e67e'
in $convert with no onError value: Input is not a valid base64
string.` |
| `{
   input: "hn3uUsMxSE6S0cVkebjmfg==",
   to: {
      type: "binData",
      subtype: 4
   },
   format: "base64"
}` | `Failed to parse BinData 'hn3uUsMxSE6S0cVkebjmfg==' in $convert
with no onError value: Input is not a valid base64 string.` |
| `{
   input: "867dee52-c331-484e-92d1-c56479b8e67e",
   to: {
      type: "binData",
      subtype: 4
   },
   format: "uuid"
}` | `UUID('867dee52-c331-484e-92d1-c56479b8e67e')` |
| `{
   input: "äöäöä",
   to: {
      type: "binData",
      subtype: 4
   },
   format: "uuid"
}` | `Failed to parse BinData 'äöäöä' in $convert with no onError
value: Input is not a valid UUID string.` |
| `{
   input: "867dee52-c331-484e-92d1-c56479b8e67e",
   to: { type: "binData" },
   format: "uuid"
}` | `Failed to parse BinData '867dee52-c331-484e-92d1-c56479b8e67e'
in $convert with no onError value: Only the UUID subtype (4)
is allowed with the 'uuid' format.` |

**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](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-JSON) array. |
| Null or Missing | Returns null. |

The following table lists some conversion of string to array examples:

| Example | Results |
| --- | --- |
| `{ input: "[1, 2, 3]", to: "array" }` | [ 1, 2, 3 ] |
| `{ input: '["a", "b", "c"]', to: "array" }` | [ 'a', 'b', 'c' ] |
| `{ input: "[]", to: "array" }` | [ ] |
| `{ input: "{}", to: "array" }` | Error: Input doesn't match expected type 'array' |
| `{ input: 123, to: "array" }` | Error: Unsupported conversion from int to array in $convert with no onError value |
| `{ input: "123", to: "array" }` | Error: Input doesn't represent valid JSON: Unexpected standalone value |
| `{ input: "[{\"$oid\": \"507f1f77bcf86cd799439011\"}]", to:
"array" }` | [ { '$oid': '507f1f77bcf86cd799439011' } ] |
| `{ input: "[1, 2, 3]", to: "array", format: "base64url" }` | [ 1, 2, 3 ] |
| `{ input: "asdf", to: "array", onError: "on error!" }` | 'on error!' |
| `{ input: null, to: "array", onNull: "on null!" }` | '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**:

```javascript
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=") }
])

```

```javascript
db.t.aggregate([
  {
    $project: {
      _id: 0,
      original: "$v",
      asArray: {
        $convert: {
          input: "$v",
          to: { type: "array" }
        }
      }
    }
  }
])

```

**Output**:

```javascript
[
  { 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](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-JSON) object. |
| Null or Missing | Returns null. |

The following table lists some conversion to object examples:

| Example | Results |
| --- | --- |
| `{ input: "{\"a\": 1, \"b\": 2}", to: "object" }` | { a: 1, b: 2 } |
| `{ input: "{}", to: "object" }` | { } |
| `{ input: "[]", to: "object" }` | Error: Input doesn't match expected type 'object' |
| `{ input: "123", to: "object" }` | Error: Input doesn't represent valid JSON: Unexpected standalone value |
| `{ input: "{\"nam\\u0000e\": \"foo\"}", to: "object" }` | Error: Input doesn't represent valid JSON: Illegal embedded null byte |
| `{ input: "{\"name\": \"fo\\u0000o\"}", to: "object" }` | { name: 'fox00o' } |
| `{ input: "{\"a\": 1, \"b\": 2, \"a\": 3}", to: "object" }` | { a: 3, b: 2 } |
| `{ input: "{\"foo\": null}", to: "object" }` | { foo: null } |
| `{ input: "{\"foo\": false}", to: "object" }` | { foo: false } |
| `{ input: "{\"__proto__\": {\"foo\": null}}", to: "object" }` | { ['__proto__']: { foo: null } } |
| `{ input: "{\"foo\": \"NaN\"}", to: "object" }` | { foo: 'NaN' } |
| `{ input: "{\"foo\": 123}", to: "object" }` | { foo: 123 } |
| `{ input: "{\"foo\": 4294967296}", to: "object" }` | { foo: Long('4294967296') } |
| `{ input: "{\"foo\": 1.123123}", to: "object" }` | { foo: 1.123123 } |
| `{ input: "{\"foo\": 1.2e+3}", to: "object" }` | { foo: 1200 } |
| `{ input: "{\"largePos\": 18446744073709551615}", to: "object" }` | { largePos: 18446744073709552000 } |
| `{ input: "{\"largeNeg\": -18446744073709551615}", to: "object" }` | { largeNeg: -18446744073709552000 } |
| `{ input: null, to: "object" }` | null |
| `{
   input: "{\"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]}", to: "object"
}` | {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 zeroReturn false if zero |
| Double | Returns true if not zeroReturn false if zero |
| Integer | Returns true if not zeroReturn false if zero |
| JavaScript | Returns true |
| Long | Returns true if not zeroReturn false if zero |
| MaxKey | Returns true |
| MinKey | Returns true |
| Null | Returns the value specified for the `onNull` option. By default, returns null. |
| 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 [MongoDB BSON Types.](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-bson-types)

The following table lists some conversion to boolean examples:

| Example | Results |
| --- | --- |
| `{ input: true, to: "bool" }` | true |
| `{ input: false, to: "bool" }` | false |
| `{ input: 1.99999, to: "bool" }` | true |
| `{ input: Decimal128( "5" ), to: "bool" }` | true |
| `{ input: Decimal128( "0" ), to: "bool" }` | false |
| `{ input: 100, to: "bool" }` | true |
| `{
   input: ISODate( "2018-03-26T04:38:28.044Z" ),
   to: "bool"
}` | true |
| `{ input: "hello", to: "bool" }` | true |
| `{ input: "false", to: "bool" }` | true |
| `{ input: "", to: "bool" }` | true |
| `{ input: null, to: "bool" }` | 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 `binData` value as an integer. `binData` is interpreted as two's signed complement signed integer. The number of bytes in the `binData` value must be `1`, `2`, or `4`. If the `input` is of an unexpected length an error is generated. You can control this behavior by configuring `$convert.onError`. |
| 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 `base` or set to `null`, the string value must be a valid base 10 integer and fall within the minimum and maximum value for an integer. If you specify `base`, the string must only contain digits valid in that base. Prefixes, such as `"0x"`, are not allowed. The resulting integer must be within the minimum and maximum value for an integer. |

The following table lists some conversion to integer examples:

| Example | Results |
| --- | --- |
| `{ input: true, to: "int" }` | 1 |
| `{ input: false, to: "int" }` | 0 |
| `{ input: 1.99999, to: "int" }` | 1 |
| `{ input: Decimal128( "5.5000" ), to: "int" }` | 5 |
| `{
   input: Decimal128( "9223372036000.000" ),
   to: "int"
}` | Error |
| `{ input: Long( "5000" ), to: "int" }` | 5000 |
| `{ input: Long( "922337203600" ), to: "int" }` | Error |
| `{ input: "-2", to: "int" }` | -2 |
| `{ input: "2.5", to: "int" }` | Error |
| `{ input: null, to: "int" }` | null |
| `{
   input: Binary(Buffer.from("00100000", "hex"), 0),
   to: "int",
   byteOrder: "big",
}` | 1048576 |
| `{
   input: Binary(Buffer.from("FFFFE796", "hex"), 0),
   to: "int",
}` | -1763180545 |
| `{
   input: Binary(Buffer.from("001000000000000", "hex"), 0),
   to: "int",
   byteOrder: "big",
}` | 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 `base` or set to `null`, the string value must be a valid base 10 decimal and fall within the minimum and maximum value for a decimal. If you specify `base`, the string must only contain digits valid in that base. Prefixes, such as `"0x"`, are not allowed. The resulting decimal must be within the minimum and maximum value for a decimal. |
| 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 |
| --- | --- |
| `{ input: true, to: "decimal" }` | Decimal128("1") |
| `{ input: false, to: "decimal" }` | Decimal128("0") |
| `{ input: 2.5, to: "decimal" }` | Decimal128( "2.50000000000000" ) |
| `{ input: Int32( 5 ), to: "decimal" }` | Decimal128("5") |
| `{ input: Long( 10000 ), to: "decimal" }` | Decimal128("10000") |
| `{ input: "-5.5", to: "decimal" }` | Decimal128("-5.5") |
| `{
   input: ISODate( "2018-03-26T04:38:28.044Z" ),
   to: "decimal"
}` | 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 `binData` value as a double. `binData` is interpreted as an IEEE 754 single-precision or double-precision floating point. The number of bytes in the `binData` value must be `4` or `8`. If the `input` is of an unexpected length an error is generated. You can control this behavior by configuring `$convert.onError`. |
| 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 `base` or set to `null`, the string value must be a valid base 10 double and fall within the minimum and maximum value for a double. If you specify `base`, the string must only contain digits valid in that base. Prefixes, such as `"0x"`, are not allowed. The resulting double must be within the minimum and maximum value for a double. |
| 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 |
| --- | --- |
| `{ input: true, to: "double" }` | 1 |
| `{ input: false, to: "double" }` | 0 |
| `{ input: 2.5, to: "double" }` | 2.5 |
| `{ input: Int32( 5 ), to: "double" }` | 5 |
| `{ input: Long( "10000" ), to: "double" }` | 10000 |
| `{ input: "-5.5", to: "double" }` | -5.5 |
| `{ input: "5e10", to: "double" }` | 50000000000 |
| `{
   input: ISODate( "2018-03-26T04:38:28.044Z" ),
   to: "double"
}` | 1522039108044 |
| `{
   input: Binary(Buffer.from("04CCCCCD", "hex"), 0),
   to: "double",
   byteOrder: "big",
}` | 4.814824932714571e-36 |
| `{
   input: Binary(Buffer.from("0000", "hex"), 0),
   to: "double",
   byteOrder: "big",
}` | 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](https://en.wikipedia.org/wiki/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:

```javascript
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:

```none
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 `binData` value as a long. `binData` is interpreted as two's signed complement signed integer. The number of bytes in the `binData` value must be `1`, `2`, `4` or `8`. If the `input` is of an unexpected length an error is generated. You can control this behavior by configuring `$convert.onError`. |
| 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 `base` or set to `null`, the string value must be a valid base 10 long and fall within the minimum and maximum value for a long. If you specify `base`, the string must only contain digits valid in that base. Prefixes, such as `"0x"`, are not allowed. The resulting long must be within the minimum and maximum value for a long. |
| Date | Converts the Date into the number of milliseconds since the epoch. |

The following table lists some conversion to long examples:

| Example | Results |
| --- | --- |
| `{ input: true, to: "long" }` | Long("1") |
| `{ input: false, to: "long"  }` | Long("0") |
| `{ input: 2.5, to: "long"  }` | Long("2") |
| `{ input: Decimal128( "5.5000" ), to: "long" }` | Long("5") |
| `{
   input: Decimal128( "9223372036854775808.0" ),
   to: "long"
}` | Error |
| `{ input: Int32( 8 ), to: "long" }` | Long("8") |
| `{
   input: ISODate( "2018-03-26T04:38:28.044Z" ),
   to: "long"
}` | Long("1522039108044") |
| `{ input: "-2", to: "long" }` | Long("-2") |
| `{ input: "2.5", to: "long" }` | Error |
| `{ input: null, to: "long" }` | null |
| `{
   input: Binary(Buffer.from("001000000", "hex"), 0),
   to: "long",
   byteOrder: "big",
}` | 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: "2018-03-03"; "2018-03-03T12:00:00Z"; "2018-03-03T12:00:00+0500" |
| 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 |
| --- | --- |
| `{
   input: 120000000000.5,
   to: "date"
}` | ISODate("1973-10-20T21:20:00.000Z") |
| `{
   input: Decimal128( "1253372036000.50" ),
   to: "date"
}` | ISODate("2009-09-19T14:53:56.000Z") |
| `{
   input: Long( "1100000000000" ),
   to: "date
}` | ISODate("2004-11-09T11:33:20.000Z") |
| `{
   input:  Long( "-1100000000000" ),
   to: "date"
}` | ISODate("1935-02-22T12:26:40.000Z") |
| `{
   input: ObjectId( "5ab9c3da31c2ab715d421285" ),
   to: "date"
}` | ISODate("2018-03-27T04:08:58.000Z") |
| `{ input:  "2018-03-03", to: "date" }` | ISODate("2018-03-03T00:00:00.000Z") |
| `{
   input: "2018-03-20 11:00:06 +0500",
   to: "date"
}` | ISODate("2018-03-20T06:00:06.000Z") |
| `{ input: "Friday", to: "date" }` | Error |
| `{
   input: Timestamp( { t: 1637688118, i: 1 } ),
   to: "date"
}` | 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 |
| --- | --- |
| `{
   input: "5ab9cbfa31c2ab715d42129e",
   to: "objectId"
}` | ObjectId("5ab9cbfa31c2ab715d42129e") |
| `{
   input: "5ab9cbfa31c2ab715d42129",
   to: "objectId"
}` | Error |

### Convert to String

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

| Input Type | Behavior |
| --- | --- |
| Array | Returns the [`Array`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Array) as a string. **New in version 8.3** |
| BinData | If the [`BinData`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Binary) is a UUID, returns the UUID as a string. Otherwise, returns the base64 encoded string value. |
| Boolean | Returns the Boolean value as a string. |
| Date | Returns the [`Date`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Date) as a string. |
| Decimal | Returns the [`Decimal`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Decimal128) value as a string. |
| Double | Returns the [`Double`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Double) value as a string. |
| Integer | Returns the [`Integer`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int32) value as a string. |
| Long | Returns the [`Long`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int64) value as a string. |
| MaxKey | Returns the [`MaxKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-MaxKey) as a string. **New in version 8.3** |
| MinKey | Returns the [`MinKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-MinKey) as a string. **New in version 8.3** |
| Object | Returns the object as a string. **New in version 8.3** |
| ObjectId | Returns the [`ObjectId`](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-ObjectId) value as a hexadecimal string. |
| Regular Expression | Returns the [`Regular Expression`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Regular-Expression) as a string. **New in version 8.3** |
| String | No operation. Returns the string value. |
| Timestamp | Returns the [`Timestamp`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Timestamp) as a string. **New in version 8.3** |

**Note:**

When you specify `base` and the `input` is a numeric type, [`$convert`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#mongodb-expression-exp.-convert) returns the string representation of the integer value in that base. Base conversion for strings is only supported for integer values, otherwise [`$convert`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert.md#mongodb-expression-exp.-convert) returns a conversion error unless you specify `onError`.

The following table lists some conversion to string examples:

| Example | Results |
| --- | --- |
| `{ input: true, to: "string" }` | "true" |
| `{ input: false, to: "string" }` | "false" |
| `{ input: 2.5, to: "string" }` | "2.5" |
| `{ input: Int32( 2 ), to: "string" }` | "2" |
| `{ input:  Long( 1000 ), to: "string" }` | "1000" |
| `{
   input: ObjectId( "5ab9c3da31c2ab715d421285" ),
   to: "string"
}` | "5ab9c3da31c2ab715d421285" |
| `{
   input:  ISODate( "2018-03-27T16:58:51.538Z" ),
   to: "string"
}` | "2018-03-27T16:58:51.538Z" |
| `{
   input: BinData(4, "hn3f"),
   to: "string",
   format: "base64"
}` | 'hn3f' |
| `{
   input: 10.5,
   to: "string",
   base: 2,
   onError: "invalid"
}` | "invalid" |

## Examples

The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). 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:

```javascript
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 } }
      }
   }
] )

```

**Output:**

```javascript
[
  {
    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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage selects three movies that illustrate each conversion outcome:

```javascript
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 } }
] )

```

**Output:**

```javascript
[
  {
    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`.

**Note:**

These examples use [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh). The default types are different in the legacy [`mongo`](https://www.mongodb.com/docs/manual/reference/mongo.md#mongodb-binary-bin.mongo) shell.

## Learn More

- Convert a value to an array with [`$toArray`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toarray.md#mongodb-expression-exp.-toArray)

- Convert a string to an object with [`$toObject`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toobject.md#mongodb-expression-exp.-toObject)

- Convert a value to a boolean with [`$toBool`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tobool.md#mongodb-expression-exp.-toBool)

- Convert a value to an integer with [`$toInt`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toint.md#mongodb-expression-exp.-toInt)

- Convert a value to a decimal with [`$toDecimal`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todecimal.md#mongodb-expression-exp.-toDecimal)

- Convert a value to a double with [`$toDouble`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todouble.md#mongodb-expression-exp.-toDouble)

- Convert a value to a long with [`$toLong`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tolong.md#mongodb-expression-exp.-toLong)

- Convert a value to a date with [`$toDate`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/todate.md#mongodb-expression-exp.-toDate)

- Convert a value to an ObjectId with [`$toObjectId`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toobjectid.md#mongodb-expression-exp.-toObjectId)

- Convert a value to a string with [`$toString`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/tostring.md#mongodb-expression-exp.-toString)

- Convert a date string to a date object with [`$dateFromString`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/datefromstring.md#mongodb-expression-exp.-dateFromString)

- Convert a date object to a string with [`$dateToString`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/datetostring.md#mongodb-expression-exp.-dateToString)
