skip to content

Extended Type System

BSON's type table goes well past JSON: binary subtypes, Decimal128, Regex, MinKey and MaxKey, and a few deprecated codes. Interviewers ask how a value is really stored and how UUIDs went wrong.

on this pageshow

explore

questions

6

Which value types does BSON add beyond JSON's, and how does a reader tell which type a value has?

level: juniorimportance: should knowfreq 25%

answer

  1. one byte before every key
  2. JSON's number splits into four
  3. raw bytes, dates, regexes, exact decimals
  4. two markers with no value bytes

basics

~20 s

BSON adds int32, int64, decimal128, binary, ObjectId, UTC datetime, regular expression, Timestamp, JavaScript code, MinKey and MaxKey to JSON's types. A one-byte type code in front of each element names the type and so tells a reader how to read the value.

solid answer

~40 s

JSON has strings, numbers, objects, arrays, booleans and null. BSON keeps those and widens them: a number becomes `double`, `int32`, `int64` or `decimal128`, and it adds `binData` with a subtype, ObjectId, a UTC datetime, regular expressions, Timestamp, JavaScript code, and the MinKey and MaxKey markers. Each element starts with a one-byte type code, then the key as a `cstring`, then the value. An element has no length field of its own, so only the code tells a reader where the value ends. That means a reader that does not recognize a code cannot find the next element and has to stop with an error.

code

plaintext · 9 lines
plaintext
14 00 00 00   document length: 20
10            type code: int32
61 00         key "a" as a cstring
05 00 00 00   value: 5, little-endian
02            type code: string
62 00         key "b" as a cstring
01 00 00 00   string length: 1 (just the trailing NUL)
00            the string's trailing NUL
00            document terminator

go deeper

for a junior

Recall the shape: type code, key, value. Then name the types JSON lacks: sized integers, decimal128, binary, ObjectId, datetime, regex, Timestamp and the two key markers.

for a middle

Explain that an element has no length of its own, and that each code selects a layout: fixed width, length-prefixed, cstrings or nothing at all.

for a senior

Connect the table to failures you can see: a client older than a newly added code cannot read past it, while an unfamiliar binary subtype passes through. That shapes how a format can grow.

for a principal

Treat the type table as a compatibility surface. A new code breaks every older reader, so ask how a format evolves when its readers are deployed separately from its writers.

## What the type table is **BSON** is a binary format for ordered key/value documents, specified at bsonspec.org as version 1.1. JSON has six kinds of value: string, number, object, array, boolean and null. BSON keeps each of those and adds more, and its **type table** lists them all. Every element in a BSON document has the same three-part shape: 1. A one-byte **type code**. 2. The key, written as a `cstring`: bytes ending in a NUL. 3. The value, in whatever layout that code defines. ## The table These are the live codes, shown in hex. The right-hand column is what follows the key. | Code | Type | Value bytes | |---|---|---| | `\x01` | `double` | 8 | | `\x02` | string | `int32` length, UTF-8 bytes, NUL | | `\x03` | embedded document | a whole document | | `\x04` | array | a document with keys `0`, `1`, and so on | | `\x05` | binary (`binData`) | `int32` length, subtype byte, data | | `\x07` | ObjectId | 12 | | `\x08` | boolean | 1 | | `\x09` | UTC datetime | 8, an `int64` of milliseconds | | `\x0A` | null | 0 | | `\x0B` | regular expression | two `cstring`s | | `\x0D` | JavaScript code | string layout | | `\x10` | `int32` | 4 | | `\x11` | Timestamp | 8, a `uint64` | | `\x12` | `int64` | 8 | | `\x13` | `decimal128` | 16 | | `\xFF` | MinKey | 0 | | `\x7F` | MaxKey | 0 | Four more codes, `\x06`, `\x0C`, `\x0E` and `\x0F`, are marked deprecated but remain in the grammar. ## What the extra types buy JSON has to carry these through conventions that a parser cannot tell from ordinary data. BSON gives each a code, so the type travels with the value: - **Integers with a declared width.** A JSON number has no width of its own; `int32` and `int64` state theirs. - **Exact decimals.** `decimal128` is a 128-bit IEEE 754-2008 decimal floating point value. - **Raw bytes.** JSON needs a text encoding such as base64; `binData` holds the bytes unchanged, with a subtype naming what they are. - **Dates.** JSON has no date type. The UTC datetime is an `int64` of milliseconds since the Unix epoch. - **Regular expressions.** A pattern and its options are stored as a typed pair instead of a string that some reader must know to compile. ## MinKey and MaxKey **MinKey** and **MaxKey** are the odd pair. Their code is their whole content: there are no value bytes at all. The specification defines MinKey as comparing lower than all other element values and MaxKey as comparing higher, so being the extreme comes from the type and not from a stored number. Two details catch people out: - MinKey's code is `signed_byte(-1)`, which a hex dump shows as `FF`. MaxKey's is `signed_byte(127)`, shown as `7F`. - A document holding only `{a: MinKey}` takes 8 bytes: a 4-byte document length, the code, the key `a` and its NUL, and the terminating NUL. ```plaintext 08 00 00 00 document length: 8, counting these four bytes FF type code: MinKey 61 00 key "a" as a cstring 00 document terminator ``` ## Why an unknown code stops a reader An element carries no general length field. A string's value starts with a length, an `int32` is a fixed 4 bytes, and a regular expression has no length at all and ends at its second NUL. Only the code says which rule applies. So a reader that meets a code it does not know cannot work out where the next element begins, and the safe move is to fail. PyMongo 4.19, for one, raises `InvalidBSON` with the message `Detected unknown BSON type`, and asks whether you are on the latest driver. That is different from an unfamiliar binary **subtype**, where the `int32` length still says how far to go. That difference is why a format can add a new kind of data as a subtype without breaking older readers, the argument the encryption specification makes for its own subtype. ## What the table does not do - It is not a schema. A code describes one element, so the same key can hold different types in different documents. - It says nothing about how a database uses a type. Choosing among the numeric types, reading an ObjectId's parts and ordering values of different types are separate questions, answered by the database and not by the format's table.

  • Why can a reader jump past an embedded document it does not care about, yet not past an element of unknown type?
    An embedded document starts with an `int32` holding its total size, so a reader that recognizes code `\x03` can jump straight past it. That jump depends on knowing the code. With an unknown code the reader cannot tell whether the next bytes are a length, a fixed-width number or a `cstring`, so no jump is safe.
  • Is MinKey stored as a very small number?
    No. MinKey has the code `\xFF` and no value bytes, so there is no number to read. The BSON specification defines it as comparing lower than every other element value. Its position comes from the type itself, which is why no real value can ever fall below it.

  • BSON stores every number as a double, because JSON has only one number type.
  • Every BSON element has a length field, so a reader can skip any unknown type.
  • MinKey stores a very large negative number in its value bytes.
  • BSON type codes act as a schema that fixes a key's type across documents.
  • A BSON array has its own element count instead of being a document with numeric keys.
open as a page

How is a BSON binary value laid out, and what does its subtype byte tell a reader?

level: middleimportance: should knowfreq 22%

basics

~20 s

A BSON binary value is an int32 byte count, one subtype byte, then the data; the count excludes the subtype. The subtype names what the bytes mean, such as generic, UUID or vector, so new kinds of data need no new type code.

open as a page

How does BSON's decimal128 type lay out a number in its 16 bytes, and why do 2.00 and 2.0 differ?

level: middleimportance: should knowfreq 20%

basics

~20 s

BSON decimal128 stores IEEE 754-2008 128-bit decimal in 16 little-endian bytes: a sign bit, a 14-bit biased exponent and a binary integer coefficient. It never normalizes, so 2.00 is 200E-2 and 2.0 is 20E-1: equal values, different bytes.

open as a page

A BSON field holds subtype 3 UUIDs from services on different MongoDB drivers, and the decoded values look scrambled: what do the raw bytes show, and what can they not prove?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Legacy subtype 3 records no byte order: the Java and C# legacy encodings reorder the 16 bytes, while subtype 4 always means RFC 4122 order. Across many random UUIDs, where the version nibble lands points to the writer, as evidence and not proof.

open as a page

How many bytes do BSON Regex and Timestamp values occupy, and how is each one laid out?

level: middleimportance: nice to knowfreq 12%

basics

~20 s

A BSON Regex is two cstrings, pattern then options, so its size is both lengths plus two NULs, with options stored alphabetically. A Timestamp is always 8 bytes: a uint64 whose first 4 bytes are the increment and last 4 the seconds.

open as a page

A BSON reader meets deprecated type codes 6, 12, 14 or 15 in old data: what are they, and how should it handle them?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Codes 6, 12, 14 and 15 are Undefined, DBPointer, Symbol and code with scope. Deprecated means new data should avoid them, not that they are invalid: read them by layout, never emit them, and expect a driver's mapping to change them on rewrite.

open as a page