skip to content

A pipeline converts BSON documents to plain JSON and back before reloading them: which values come back changed, and why?

level: seniorimportance: should knowfreq 28%

answer

  1. what JSON has no word for
  2. one number syntax, many BSON numbers
  3. strings wearing a date's clothes
  4. large integers and IEEE 754
  5. queries that quietly stop matching

basics

~20 s

Values plain JSON has no type for change: dates, ObjectIds and binary data return as strings or bare numbers, numeric types collapse into one syntax, large int64 values can lose precision, and NaN has no JSON form.

solid answer

~40 s

Plain JSON has strings, numbers, booleans, null, objects and arrays, so the rest of BSON must be flattened to those. Typically a datetime becomes a string or a number, an ObjectId a hex string, and `binData` encoded text with its subtype gone. `int32`, `int64` and `double` share one number syntax, so the reloader chooses again, and a parser that uses IEEE 754 doubles turns `9007199254740993` into `9007199254740992` with no error. Nothing fails at conversion time. The damage shows later: in MongoDB 9.0 a date range query skips the strings, because range operators bracket by type, and an `_id` lookup by ObjectId no longer matches. To find it, group by `$type` per field. To avoid it, keep BSON for reloads, or use Extended JSON where text is required and accept the extra bytes.

code

javascript · 5 lines
javascript
db.events.aggregate([
  { $group: { _id: { $type: "$createdAt" }, n: { $sum: 1 } } }
])
// A healthy field returns one group, for example { _id: "date", n: 1200000 }.
// A second group such as { _id: "string", n: 40000 } shows what the pipeline rewrote.

go deeper

for a junior

Recall that plain JSON has no date, binary or ObjectId types and only one number syntax, so those values cannot return with their original type.

for a middle

Explain the mapping type by type, and why it cannot be reversed: a string holding a date looks like any other string, and a large integer can be rounded by a double-based parser.

for a senior

Show the diagnosis: nothing errors at conversion, the symptom is a query or join that quietly misses documents, and grouping by type per field finds the damage.

for a principal

Set a rule for the organisation's pipelines: which paths must stay binary, who owns any text mapping, and how a type check guards a reload before it reaches production data.

## Why values change Plain **JSON** has six kinds of value: string, number, boolean, null, object and array. **BSON** has many more, including `int32`, `int64`, `double`, `decimal128`, a UTC datetime, `ObjectId` and `binData`. A converter to plain JSON has to map each of those onto the six, and the mapping is one-way: a string that holds a date looks exactly like any other string, so nothing tells the return path to rebuild the date. The conversion raises no error. The output is valid JSON and the reload succeeds, which is what makes this a production problem and not a build failure. ## What happens to each type The exact mapping belongs to the converter. These are the common outcomes: | BSON value | Typical plain JSON | What comes back | |---|---|---| | `string`, `boolean`, `null` | The same | Unchanged | | Embedded document, array | Object, array | Same structure, values mapped in turn | | `int32` | Number | A number; the reloader picks the type | | `int64` above 2^53 | Number | Can be rounded if the reader uses doubles | | `double` `1.0` | `1.0` or `1` | Possibly an integer type | | UTC datetime | ISO-8601 string or millisecond number | `string` or a number, not a date | | `ObjectId` | 24-character hex string | `string` | | `binData` | Encoded text | `string`, with the subtype gone | | `NaN`, `Infinity` | No JSON form | An error or a substitute such as `null` | | Min key, max key | No JSON form | Lost or a wrapper object | Two of these need a closer look. - **Large integers.** JSON's number syntax has no width. A parser that decodes numbers as IEEE 754 doubles keeps every integer exactly only up to 2^53, so `9007199254740993` silently becomes `9007199254740992`. The Extended JSON specification notes that language-native JSON decoders may not distinguish numeric type when parsing. - **Field order.** BSON documents are ordered, and the Extended JSON specification says JSON objects are inherently unordered. A converter that passes through a hash map can reorder fields. ## How it shows up in production Nothing looks wrong until the data is used. In MongoDB 9.0: - A range query on a date field returns nothing for the affected documents. The inequality operators use **type bracketing**, so a `$gte` with a date operand does not match a string value. - A lookup by `ObjectId` misses documents whose `_id` is now a string. - Documents written before and after the pipeline hold mixed types in one field, so sorting and aggregation can give results that look plausible and are wrong. - An identifier that rounded may collide with a neighbour or match nothing. ## Diagnosing it 1. Pick the fields that should hold typed values: dates, identifiers, large counters and binary. 2. Group by the `$type` aggregation operator, which returns the type as a string. More than one type in a field means something rewrote it. 3. For suspected rounding, compare the same document's value at the source and after reload, using exact digits. 4. Read the converter's mapping and write down what it does for each type. Do not infer it from one sample. ## Keeping the types - **Stay in BSON for reloads.** A BSON-to-BSON path has nothing to flatten. - **Use Extended JSON where text is required.** Its type wrappers, such as `{"$numberLong":"..."}` and `{"$date":...}`, carry what plain JSON cannot, though it is a text format with limits of its own, so prefer BSON for a reload. - **Re-apply types at the boundary.** A loader with an explicit field-to-type mapping can rebuild dates and identifiers, as long as someone owns that mapping. ## What the fidelity costs in bytes Plain JSON is often smaller partly because it says less. Carrying the type in text costs more than BSON's single type byte: | Document | Plain JSON | BSON | Canonical Extended JSON | |---|---|---|---| | The integer 1 under key `n` | 7 | 12 | 24 | | The long `9007199254740993` under key `n` | 22 | 16 | 40 | So "JSON is smaller" compares a document with its types against one without them. When a text format has to keep the types, it can be larger than BSON.

  • How would you stop a damaged reload reaching production data?
    Check types at the boundary. Load into a staging collection, group by `$type` per field, and fail the run on any field with an unexpected or second type. Compare exact digits for large counters. A `$jsonSchema` validator with `bsonType: "date"` on the target then rejects a string in a date field at write time, instead of leaving it for a query to miss.
  • Why does a reload succeed when the values have been damaged?
    Because each step is valid on its own. A date held as a string is still a legal JSON string and a legal BSON string, and the store accepts it unless schema validation says otherwise. The damage is a change of meaning, not of syntax. So it appears later, in queries, sorts and joins, and only a check of types per field will find it early.

  • JSON's numbers have no size limit, so a parser never changes a large int64.
  • A failed type conversion always raises an error during the export or the reload.
  • A date that comes back as an ISO-8601 string still matches a date range query.
  • The JSON standard fixes how a converter must write a BSON date.
  • Base64 text keeps a binData value's subtype, so plain JSON loses nothing there.

Assumes MongoDB 9.0 for type bracketing and the $type operator; what plain JSON cannot hold comes from BSON 1.1 and carries no version.