> This page location: /docs.md > /docs/development.md > /docs/manual/reference/bson-types.md

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

# MongoDB Extended JSON (v2)

**Important: Disambiguation**

The following page discusses MongoDB Extended JSON v2. For discussion on the Legacy MongoDB Extended JSON v1, see [MongoDB Extended JSON (v1).](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json-v1.md)

For supported data types in [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), see [mongosh Data Types.](https://www.mongodb.com/docs/mongodb-shell/reference/data-types/)

[JSON](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-JSON) can only directly represent a subset of the types supported by [BSON](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-BSON). To preserve type information, MongoDB adds the following extensions to the JSON format.

- Canonical Mode

  A string format that emphasizes type preservation at the expense of readability and interoperability. That is, conversion from canonical to BSON generally preserves type information except in certain specific cases.

- Relaxed Mode

  A string format that emphasizes readability and interoperability at the expense of type preservation. That is, conversion from relaxed format to BSON can lose type information.

Both formats conform to the [JSON RFC](http://www.json.org) and can be parsed by the various MongoDB drivers and tools.

## MongoDB Extended JSON v2 Usage

### Drivers

The following drivers support Extended JSON v2.0:

- C

- C#

- C++

- Go

- Java

- Kotlin

- Node

- Perl

- PHPC

- Python

- Ruby

- Scala

### Extended JSON Methods

MongoDB provides the following methods for Extended JSON:

| Method | Description |
| --- | --- |
| `serialize` | Serializes a BSON object and returns the data in Extended JSON format. `EJSON.serialize( db.<collection>.findOne() )` |
| `deserialize` | Converts a serialized document to field and value pairs. The values have [BSON types.](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-type-representations) `EJSON.deserialize( <serialized object> )` |
| `stringify` | Converts the element and [type](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-type-representations) pairs in a deserialized object to strings. `EJSON.stringify( <deserialized object> )` |
| `parse` | Converts strings into element and [type](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-type-representations) pairs. `EJSON.parse( <string> )` |

For usage examples, see [Extended JSON Object Conversions](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-ex-obj-conversions) below.

For additional details, see the documentation for:

- [MongoDB NodeJS Driver](https://mongodb.github.io/node-mongodb-native/4.0/)

- [BSON Parser](https://github.com/mongodb-js/bson-ext)

- [BSON-EXT Parser](https://github.com/mongodb-js/bson-ext)

### MongoDB Database Tools

Starting in version 4.2:

| Binary | Changes |
| --- | --- |
| [`bsondump`](https://www.mongodb.com/docs/database-tools/bsondump.md#mongodb-binary-bin.bsondump) | Uses Extended JSON v2.0 (Canonical mode) format. |
| [`mongodump`](https://www.mongodb.com/docs/database-tools/mongodump.md#mongodb-binary-bin.mongodump) | Use Extended JSON v2.0 (Canonical mode) format for the metadata. Requires [`mongorestore`](https://www.mongodb.com/docs/database-tools/mongorestore.md#mongodb-binary-bin.mongorestore) version 4.2 or later that supports Extended JSON v2.0 (Canonical mode or Relaxed) format. In general, use corresponding versions of [`mongodump`](https://www.mongodb.com/docs/database-tools/mongodump.md#mongodb-binary-bin.mongodump) and [`mongorestore`](https://www.mongodb.com/docs/database-tools/mongorestore.md#mongodb-binary-bin.mongorestore). To restore data files created with a specific version of [`mongodump`](https://www.mongodb.com/docs/database-tools/mongodump.md#mongodb-binary-bin.mongodump), use the corresponding version of [`mongorestore`.](https://www.mongodb.com/docs/database-tools/mongorestore.md#mongodb-binary-bin.mongorestore) |
| [`mongoexport`](https://www.mongodb.com/docs/database-tools/mongoexport.md#mongodb-binary-bin.mongoexport) | Creates output data in Extended JSON v2.0 (Relaxed mode) by default. Creates output data in Extended JSON v2.0 (Canonical mode) if used with `--jsonFormat`. |
| [`mongoimport`](https://www.mongodb.com/docs/database-tools/mongoimport.md#mongodb-binary-bin.mongoimport) | Expects import data to be in Extended JSON v2.0 (either Relaxed or Canonical mode) by default. Can recognize data that is in Extended JSON v1.0 format if the option `--legacy` is specified. In general, the versions of [`mongoexport`](https://www.mongodb.com/docs/database-tools/mongoexport.md#mongodb-binary-bin.mongoexport) and [`mongoimport`](https://www.mongodb.com/docs/database-tools/mongoimport.md#mongodb-binary-bin.mongoimport) should match. To import data created from [`mongoexport`](https://www.mongodb.com/docs/database-tools/mongoexport.md#mongodb-binary-bin.mongoexport), you should use the corresponding version of [`mongoimport`.](https://www.mongodb.com/docs/database-tools/mongoimport.md#mongodb-binary-bin.mongoimport) |

## BSON Data Types and Associated Representations

The following presents some common BSON data types and the associated representations in *Canonical* and *Relaxed*.

| [`Array`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Array); [`Binary`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Binary); [`Date`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Date) | [`Decimal128`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Decimal128); [`Document`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Document); [`Double`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Double) | [`Int32`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int32); [`Int64`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Int64); [`MaxKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-MaxKey) | [`MinKey`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-MinKey); [`ObjectId`](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-ObjectId); [`Regular Expression`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Regular-Expression); [`Timestamp`](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#mongodb-bsontype-Timestamp) |
| --- | --- | --- | --- |

The complete list is [here.](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md)

***

| Canonical | Relaxed |
| --- | --- |
| `[ <elements> ]` | `<Same as Canonical>` |

Where the array elements are as follows:

- `<elements>`

  - Array elements use Extended JSON.

  - To specify an empty array, omit the content `[ ]`.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$binary":
   {
      "base64": "<payload>",
      "subType": "<t>"
   }
}` | `<Same as Canonical>` |

Where the values are as follows:

- `"<payload>"`

  - Base64 encoded (with padding as "=") payload string.

- `"<t>"`

  - A one- or two-character hex string that corresponds to a BSON binary subtype. See the extended bson documentation [http://bsonspec.org/spec.html](http://bsonspec.org/spec.html) for subtypes available.

***

*For dates between years 1970 and 9999, inclusive*:

| Canonical | Relaxed |
| --- | --- |
| `{"$date": {"$numberLong": "<millis>"}}` | `{"$date": "<ISO-8601 Date/Time Format>"}` |

*For dates before year 1970 or after year 9999*:

| Canonical | Relaxed |
| --- | --- |
| `{"$date": {"$numberLong": "<millis>"}}` | `<Same as Canonical>` |

Where the values are as follows:

- `"<millis>"`

  - A 64-bit signed integer as string. The value represents milliseconds relative to the epoch.

- `"<ISO-8601 Date/Time Format>"`

  - A date in [ISO-8601 Internet Date/Time Format](https://tools.ietf.org/html/rfc3339#section-5.6) as string.

  - The date/time has a maximum time precision of milliseconds:

    - Fractional seconds have exactly 3 decimal places if the fractional part is non-zero.

    - Otherwise, fractional seconds SHOULD be omitted if zero.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$numberDecimal": "<number>" }` | `<Same as Canonical>` |

Where the values are as follows:

- `"<number>"`

  - A [high-precision decimal](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst) as a string.

***

| Canonical | Relaxed |
| --- | --- |
| `{ <content> }` | `<Same as Canonical>` |

Where the document contents are as follows:

- `<content>`

  - Name:value pairs that use Extended JSON.

  - To specify an empty document, omit the content `{ }`.

***

*For finite numbers*:

| Canonical | Relaxed |
| --- | --- |
| `{"$numberDouble": "<decimal string>" }` | `<non-integer number>` |

*For infinite numbers or NAN*:

| Canonical | Relaxed |
| --- | --- |
| `{"$numberDouble": <"Infinity"|"-Infinity"|"NaN"> }` | `<Same as Canonical>` |

Where the values are as follows:

- `"<decimal string>"`

  - A 64-bit signed floating point as a string.

- `<non-integer number>`

  - A non-integer number. Integer numbers are parsed as an integer instead of a double.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$numberLong": "<number>" }` | `<integer>` |

Where the values are as follows:

- `"<number>"`

  - A 64-bit signed integer as string.

- `<integer>`

  - A 64-bit signed integer.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$numberInt": "<number>" }` | `<integer>` |

Where the values are as follows:

- `"<number>"`

  - A 32-bit signed integer as a string.

- `<integer>`

  - A 32-bit signed integer.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$maxKey": 1 }` | `<Same as Canonical>` |

The MaxKey BSON data type compares higher than all other types. See [Comparison/Sort Order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-faq-dev-compare-order-for-BSON-types) for more information on comparison order for BSON types.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$minKey": 1 }` | `<Same as Canonical>` |

The MinKey BSON data type compares lower than all other types. See [Comparison/Sort Order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-faq-dev-compare-order-for-BSON-types) for more information on comparison order for BSON types.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$oid": "<ObjectId bytes>" }` | `<Same as Canonical>` |

Where the values are as follows:

- `"<ObjectId bytes>"`

  - A 24-character, big-endian hexadecimal string that represents the ObjectId bytes.

***

| Canonical | Relaxed |
| --- | --- |
| `{ "$regularExpression":
   {
      "pattern": "<regexPattern>",
      "options": "<options>"
  }
}` | `<Same as Canonical>` |

Where the values are as follows:

- `"<regexPattern>"`

  - A string that corresponds to the regular expression pattern. The string can contain valid JSON characters and unescaped double quote (`"`) characters, but may not contain unescaped forward slash (`/`) characters.

- `"<options>"`

  - A string that specifies BSON regular expression options. You must specify the options in alphabetical order. For information on the supported options, see [`$options`.](https://www.mongodb.com/docs/manual/reference/operator/query/regex.md#mongodb-query-op.-options)

***

| Canonical | Relaxed |
| --- | --- |
| `{"$timestamp": {"t": <t>, "i": <i>}}` | `<Same as Canonical>` |

Where the values are as follows:

- `<t>`

  - A positive integer for the seconds since epoch.

- `<i>`

  - A positive integer for the increment.

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

The following examples illustrate Extended JSON usage.

### Type Representations

| Example Field Name | Canonical Format | Relaxed Format |
| --- | --- | --- |
| "_id": | {"$oid":"5d505646cf6d4fe581014ab2"} | {"$oid":"5d505646cf6d4fe581014ab2"} |
| "arrayField": | ["hello",{"$numberInt":"10"}] | ["hello",10] |
| "dateField": | {"$date":{"$numberLong":"1565546054692"}} | {"$date":"2019-08-11T17:54:14.692Z"} |
| "dateBefore1970": | {"$date":{"$numberLong":"-1577923200000"}} | {"$date":{"$numberLong":"-1577923200000"}} |
| "decimal128Field": | {"$numberDecimal":"10.99"} | {"$numberDecimal":"10.99"} |
| "documentField": | {"a":"hello"} | {"a":"hello"} |
| "doubleField": | {"$numberDouble":"10.5"} | 10.5 |
| "infiniteNumber" | {"$numberDouble":"Infinity"} | {"$numberDouble":"Infinity"} |
| "int32field": | {"$numberInt":"10"} | 10 |
| "int64Field": | {"$numberLong":"50"} | 50 |
| "minKeyField": | {"$minKey":1} | {"$minKey":1} |
| "maxKeyField": | {"$maxKey":1} | {"$maxKey":1} |
| "regexField": | {"$regularExpression":{"pattern":"^H","options":"i"}} | {"$regularExpression":{"pattern":"^H","options":"i"}} |
| "timestampField": | {"$timestamp":{"t":1565545664,"i":1}} | {"$timestamp":{"t":1565545664,"i":1}} |
| "uuid": | {"$uuid":"3b241101-e2bb-4255-8caf-4136c566a962"} | {"$uuid":"3b241101-e2bb-4255-8caf-4136c566a962"} |

### Extended JSON Object Conversions

The following short examples retrieve a document object and then convert the object to different forms using Extended JSON object conversion methods.

#### EJSON.serialize

Serialize the data stored in a MongoDB document object. [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) parses a JavaScript object and returns values using `"$"` prefixed [types:](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-type-representations)

```javascript
serialized = EJSON.serialize(
   db.comments.find( {}, { _id: 1, date: 1 } ).sort( { _id: 1 } ).limit(1).next()
)

```

**Output:**

```javascript
{
  _id: {
    '$oid': '5a9427648b0beebeb69579e7'
  },
  date: {
    '$date': '2002-08-18T04:56:07.000Z'
  }
}

```

#### EJSON.deserialize

Deserialize a serialized object. [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) parses a JavaScript object and returns values using the default [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) [type](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json.md#std-label-type-representations) form:

```javascript
EJSON.deserialize( serialized )

```

**Output:**

```javascript
{
  _id: ObjectId('5a9427648b0beebeb69579e7'),
  date: ISODate('2002-08-18T04:56:07.000Z')
}

```

#### EJSON.stringify

Convert an object to a string. [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) outputs the elements of the converted object as strings:

```javascript
stringified = EJSON.stringify(
   db.comments.find( {}, { _id: 1, date: 1 } ).sort( { _id: 1 } ).limit(1).next()
)

```

**Output:**

```javascript
{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"date":{"$date":"2002-08-18T04:56:07.000Z"}}

```

#### EJSON.parse

Parse a string to create an object. [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) returns the converted strings as documents:

```javascript
EJSON.parse( stringified )

```

**Output:**

```javascript
{
  _id: ObjectId('5a9427648b0beebeb69579e7'),
  date: ISODate('2002-08-18T04:56:07.000Z')
}

```
