Which value types does BSON add beyond JSON's, and how does a reader tell which type a value has?
answer
- one byte before every key
- JSON's number splits into four
- raw bytes, dates, regexes, exact decimals
- two markers with no value bytes
basics
~20 sBSON 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 sJSON 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 lines14 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 terminatorgo deeper
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.
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.
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.
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.