Skip to main content
The MongoDB Connector’s EJSON mode converts BSON values to canonical wrappers when synchronizing Ditto and MongoDB. The client-side examples below demonstrate local canonical documents without requiring a MongoDB connection. Read more in the MongoDB Connector EJSON Mode section.

What is EJSON?

Extended JSON (EJSON) is MongoDB’s canonical representation of BSON (Binary JSON) data in JSON format. When EJSON mode is enabled in the MongoDB Connector, all BSON data types from MongoDB are converted to their canonical JSON representation before being stored in Ditto, and vice versa. This ensures complete fidelity of MongoDB’s rich data types when synchronizing with Ditto, but requires special handling in your application code and queries.

EJSON Data Type Mappings

When EJSON mode is enabled, MongoDB BSON types are converted to their canonical representations:

Common Type Conversions

For a complete list of EJSON type representations, refer to the MongoDB Extended JSON documentation.

Querying EJSON Data in DQL

When EJSON mode is enabled, you need to account for the nested structure of EJSON types in your DQL queries.

Working with Numbers

The canonical payloads of Int32, Int64, Double, and Decimal128 are strings, which affects comparison operations. Other fields, such as the t and i components of a timestamp, are JSON numbers:
For example, these SDK 5.2.0 examples select string IDs for prices in the numeric range [1000, 2000):
Call either function with min set to 1000.0 and max set to 2000.0. The lower bound is included and the upper bound is excluded; numeric comparison avoids the false positives from the string-range counterexample below. Match the cast to the wrapper in SDK 5.2.0: The price query handles $numberDouble only. A field containing $numberInt, $numberLong, or $numberDecimal needs handling for those wrappers too. A failed CAST produces MISSING, so it drops out of these range filters without throwing. For example, CAST('1500.0' AS INTEGER) produces MISSING. FLOAT is binary floating point. It can lose Decimal128 precision and is not a general-purpose conversion for exact currency arithmetic. Use an appropriate BSON/decimal library when your application needs exact decimal values.

Accessing Date Fields

Instead of directly accessing a date field, you need to traverse the EJSON structure:
Canonical EJSON dates store epoch milliseconds as strings in $date.$numberLong. The 13-digit non-negative values 1000000000000 through 9999999999999 cover 2001-09-09T01:46:40Z through 2286-11-20T17:46:39.999Z. Within that range, decimal strings with no leading zeros sort in date order. Lexicographic comparison is not generally equivalent to numeric or date comparison: different digit counts or negative values break this ordering. Use numeric comparison when the fixed-width, non-negative conditions are not guaranteed.
Bind min and max as signed 64-bit epoch milliseconds. For the start of 2024 through the start of 2025, use 1704067200000 and 1735689600000. These SDK 5.2.0 examples select IDs in the half-open date interval [min, max):
Use INTEGER to preserve the full signed 64-bit integer value. For example, 9007199254740993 stays exact with INTEGER but becomes 9007199254740992 with FLOAT. Negative millisecond values also require numeric ordering; a string comparison is not a general date-range query.
Converting EJSON numeric strings (using CAST or other conversion functions) currently makes queries ineligible for index optimization in DQL. This can significantly impact query performance on large datasets.

Updating EJSON Data

When updating EJSON data, you need to ensure that the data is updated in the correct format. Typically this means ensuring that the nested fields are updated correctly using strings to represent numeric values.

Changing Datatypes

We recommend avoiding changing the datatype of an EJSON field, aside from moving from a null type to a non-null type. For example, if you want to change the order date from a null type to a date type, you can do the following:
If you do wish to change the datatype of an EJSON field (e.g. Int32 to a Double), you can do the following:

Best Practices for EJSON Queries

1. Minimize Type Conversions

Avoid converting EJSON numeric types unless absolutely necessary, as this prevents index usage:

2. When String Comparisons Work

String equality compares the stored representation, not numeric equivalence. For range comparisons, all compared values must have a compatible fixed format. For example, the year query below assumes every stored year is a four-digit, non-negative integer string with no leading zeros. Arbitrary $numberDouble strings do not satisfy that condition:

3. Create Helper Fields

If you frequently query EJSON fields, consider creating flattened helper fields that are not stored as BSON:

Converting EJSON in Your Application

When working with EJSON data in your application (e.g. in your UIs or business logic), you’ll need to convert between EJSON and native types using platform-specific BSON libraries. You should pass the EJSON data contained in your DittoQueryResultItem to the BSON library to convert it to the native type.

Platform-Specific BSON Libraries

BSON libraries are available for most platforms, you can find a suggested (though not exhaustive) list of libraries below:

JavaScript and TypeScript Examples

Install MongoDB’s bson package in your application and import its EJSON/BSON types from that package; Ditto’s JavaScript SDK does not expose an EJSON codec. The examples assume an initialized ditto. Ditto stores the wrappers as ordinary maps and strings. It does not automatically turn them into BSON classes or validate their BSON ranges.

Store Canonical BSON Values

Use { relaxed: false } explicitly to retain canonical numeric wrappers. Construct Long and Decimal128 values from decimal strings so a JavaScript number cannot round them before serialization. new Double(42) preserves a Double marker even though its value looks integral. The ObjectId becomes a composite Ditto document ID.
The example covers ObjectId, Int32, Int64, Double, Decimal128, Date, Binary, and Timestamp. It uses valid values within their supported ranges. A BSON Date must also fit JavaScript’s Date range to be usable as a native Date.

Restore Typed Values

Pass the plain value from the query item to EJSON.deserialize. Dematerialize the item after extracting that value. With canonical decoding, numeric fields retain BSON classes such as Long, Int32, Double, and Decimal128; dates become native Date objects and binary values become BSON Binary instances.

Serialize and Parse Canonical Text

Here typed is the BSON-valued object restored above. Use EJSON.stringify and EJSON.parse with explicit canonical options to preserve BSON type markers. Ordinary JSON.parse of canonical text instead gives the plain wrapper objects suitable for storing in Ditto.

Decode Long Values as bigint

Here canonical is a plain wrapper document. Use useBigInt64: true to request native bigint values for $numberLong, while retaining the other BSON types. Avoid converting a large Long or bigint to number: that can discard integer precision. Decimal128 is not a bigint; retain its decimal representation for exact decimal processing.
BSON defaults to relaxed conversion, which can round a large Long. Canonical mode is type preservation, not complete input validation: in this version, parsing an out-of-range Int32/Int64 can wrap its value. Validate application input and ranges before constructing or parsing typed values. Malformed ObjectId values, non-integer Long strings, and invalid JSON are rejected.

Query Double and Long Wrappers

For Double payloads, use the DQL FLOAT cast target. SDK 5.2.0 rejects CAST(... AS DOUBLE) with query/invalid; the two names are not interchangeable. Here minimum is a finite JavaScript number. A failed conversion produces MISSING, so malformed or absent payloads do not match this numeric predicate.
Floating-point conversion does not preserve every Int64 or Decimal128 value. For an exact Long comparison, use INTEGER and bind a bigint within the signed 64-bit range. This example distinguishes 9007199254740993 from its preceding integer; converting both to floating point would lose that distinction.

Query Milliseconds as Integers

Here cutoffMillis is a valid JavaScript Date’s millisecond value, for example Date.parse('2024-01-01T00:00:00Z'). Integer conversion handles negative and variable-width millisecond strings without lexicographic ordering errors.

Update a Long Without Losing Precision

Pass a bigint nextCount and the target document’s id (the canonical ObjectId wrapper above, or a string ID). Reject numbers that may already be rounded and check signed 64-bit bounds before writing the decimal string back to the wrapper. Other document fields remain unchanged.

Distinguish Native Ditto Integers from EJSON

Native Ditto integer fields and EJSON wrappers are different representations. The native value below reads back as a bigint. Do not route it through Number(...), or through JSON.parse(item.jsonString()), to recover its exact integer value. JSON.stringify(item.value) also throws if it contains a bigint. For EJSON values, the canonical numeric strings avoid this ordinary-JSON problem.
Treat native integer results as number | bigint and check typeof when needed. Keep native integers within the signed 64-bit range. The Long update example checks its range before writing.

Performance Considerations

Index Eligibility

Queries that use type conversion functions (like CAST) on EJSON fields cannot use indexes. This can severely impact query performance for larger datasets.
To maintain query performance with EJSON:
  1. Avoid conversions in WHERE clauses: Design queries that work with EJSON string representations
  2. Pre-compute values: Store additional fields with converted values for frequently queried data
  3. Use compound strategies: Combine indexed fields with post-filtering for complex queries

Query Optimization Examples

The final string-range query is a counterexample: it also matches '20.0', '199.0' and '15000.0', although none of these values are numerically in [1000, 2000). Use numeric comparison for a numeric range.

Troubleshooting Common Issues

Symptom: Queries that were fast are now slow after enabling EJSON mode.Solution: Review queries for type conversions and create indexed helper fields for frequently queried EJSON data.
Symptom: Numeric comparisons return unexpected results.Solution: Remember that EJSON numbers are strings. Match CAST to the wrapper and required precision, or implement application-level comparison with a BSON library.
Symptom: Date range queries return no results.Solution: Access the nested $date.$numberLong field, cast to INTEGER, and bind min and max as epoch milliseconds: