This page follows the BSON specification version 1.1, read 2026-11-12, with the MongoDB ObjectID and Decimal128 specifications, read 2026-11-12. Numbers are little-endian except where noted.
Documents
- A document is a 4-byte total length (including itself and the final byte), the
elements, and a
00byte. - An element is a type byte, the field name as a NUL-terminated string of modified UTF-8 (cstring), and the value.
- A string value is a 4-byte length (bytes including the final NUL), the UTF-8
bytes and a
00. A cstring’s bytes must not contain00, so it is not full UTF-8; a string, being length-prefixed, has no such rule.
Element types
| Type | Name | Value |
|---|---|---|
01 | double | 8-byte IEEE 754 |
02 | string | string |
03 | embedded document | document |
04 | array | document whose keys are "0", "1", "2"… |
05 | binary | 4-byte length, subtype byte, the bytes |
06 | undefined | Deprecated; no value |
07 | ObjectId | 12 bytes; see below |
08 | boolean | 00 false, 01 true |
09 | UTC datetime | 8-byte signed milliseconds since 1970 |
0A | null | No value |
0B | regular expression | cstring pattern, cstring options in alphabetical order (the specification lists i case-insensitive, m multiline, s dotall, u Unicode \w, \W and so on, x verbose) |
0C | DBPointer | Deprecated: string and 12 bytes |
0D | JavaScript code | string |
0E | symbol | Deprecated: string |
0F | code with scope | Deprecated: 4-byte total length, string, document |
10 | 32-bit integer | 4-byte signed |
11 | timestamp | 8 bytes (uint64): the first 4 bytes are an increment, the second 4 a timestamp; an internal type used by MongoDB replication and sharding |
12 | 64-bit integer | 8-byte signed |
13 | decimal128 | 16-byte IEEE 754-2008 decimal; the coefficient is stored as a binary integer (BID), not densely packed decimal |
FF | min key | No value; compares lower than everything |
7F | max key | No value; compares higher than everything |
Binary subtypes
| Subtype | Meaning |
|---|---|
00 | Generic binary; the default for drivers and tools |
01 | Function |
02 | Binary (old): the data starts with its own 4-byte length again; deprecated in favour of 00 |
03 | UUID (old); deprecated in favour of 04 |
04 | UUID |
05 | MD5 |
06 | Encrypted BSON value |
07 | Compressed BSON column (delta, delta-of-delta and run-length encoding) |
08 | Sensitive |
09 | Vector: packed 1-bit unsigned, signed 8-bit integer or 32-bit float values, all of one type |
80–FF | User defined |
Decimal128 (type 13)
16 bytes, little-endian, holding an IEEE 754-2008 128-bit decimal in the BID
(binary integer decimal) form: the coefficient is a binary integer, not the densely
packed decimal of the standard's other encoding (the MongoDB specification, read
2026-11-13, states this and defers the bit layout to IEEE 754-2008 section 3.5.2).
IEEE 754-2008 itself is a paid standard and was not opened. The layout below was
checked against the public decoder and encoder in the MongoDB C driver
(bson-decimal128.c, read 2026-11-13: combination field mask 0x1F with
30 = infinity and 31 = NaN, exponent mask 0x3FFF, bias 6176, minimum exponent
−6176, maximum 6111, 34 digits, a significand of 2113 or more read as zero) and
against the field lengths of IBM's “Decimal Encoding Specification”
(speleotrove.com, read 2026-11-13: for decimal128 the exponent continuation is 12 bits, so with
the 2 exponent bits in the combination field the exponent is 14 bits, Elimit 12287,
Emax 6144, Emin −6143, bias 6176, a 110-bit coefficient continuation and 34 digits).
That document describes the densely packed decimal coefficient, which BSON does not use.
It holds 34 decimal digits and a range of about ±106145.
| Bits of the 128-bit value | Meaning (BID, standard form) |
|---|---|
| 127 | Sign. |
| 126–122 | Combination field. If bits 126–125 are not 11: the exponent is bits 126–113 (14 bits) and the coefficient bits 112–0. If they are 11 and bits 124–123 are not 11: the exponent is bits 124–111 and the coefficient is 0b100 followed by bits 110–0 (a value of 2113 or more, which exceeds 1034−1 and so is not a valid coefficient: such an encoding is read as zero). If bits 126–123 are 1111, the value is infinity (bit 122 = 0) or NaN (bit 122 = 1). |
| Coefficient | A binary integer of up to 113 bits (the bits after the exponent); at most 1034−1 is valid. |
| Exponent | Biased by 6176: exponent = stored − 6176, from −6176 to 6111. Value = (−1)sign × coefficient × 10exponent. |
The MongoDB specification adds these rules (these are sourced):
- Round trips must keep both value and representation (so
2.000stays2.000); drivers wrap it in a value object and do not convert it to a native decimal by default. - Overflow and underflow are errors; clamping (reducing an exponent that is too large by adding zeros to the coefficient) is silent; rounding is silent unless inexact, then an error; a bad numeric string is an error. The stated exponent is only a preferred representation: if it cannot be stored, an alternative by clamping or exact rounding must be used.
- From string: optional sign, digits with an optional point, an optional
Eand signed integer exponent, orInfinity/Inf/NaNin any case; no blanks. To string: the coefficient has no leading zeros; the adjusted exponent is exponent + (digits − 1); with exponent ≤ 0 and adjusted exponent ≥ −6 plain notation is used (a point inserted, zeros added), otherwiseEwith a sign and the adjusted exponent. Infinities print asInfinityand-Infinity; every NaN (positive, negative, signalling, with payload) prints asNaN. Other invalid representations must be treated as zero. - Extended JSON writes it as
{"$numberDecimal": "..."}using the same string rules.
Binary subtype 9: vector, and subtype 7: column
The vector subtype (MongoDB's BSON Binary Subtype 9 specification, read 2026-11-13) packs numbers of one type. The binary data is: a dtype byte, a padding byte, then the packed elements, all little-endian.
| dtype | Name | Element |
|---|---|---|
03 | INT8 | signed 8-bit integer |
27 | FLOAT32 | 32-bit float |
10 | PACKED_BIT | 1 bit each, 8 to a byte (the first element is the most significant bit: [238, 224] with padding 4 is the 12 bits 1110 1110 1110) |
Padding is the number of least-significant bits of the final byte to ignore: 0 for every
dtype except PACKED_BIT, which allows 0 to 7; a PACKED_BIT vector with padding 1 to 7
must not be empty; ignored bits should be zero (a driver should reject non-zero ones
when it writes, and may reject them when it reads). A FLOAT32 vector's data length must
be a multiple of 4. Example: 10 04 EE E0.
Subtype 7 is the compressed BSON column, described in its own section below.
Binary subtype 6: encrypted BSON value
From MongoDB's BSON Binary Encrypted specification
(mongodb/specifications, bson-binary-encrypted/binary-encrypted.md) and the
appendix of the Client Side Encryption specification, both read 2026-11-19. The first byte of the
binary data is the blob subtype, which says what follows. All values are little-endian.
| Blob subtype | Meaning | Layout after the blob subtype byte |
|---|---|---|
00 | Intent-to-encrypt marking: plaintext and how to encrypt it; used between libmongocrypt and mongocryptd and never stored | A BSON document with v (the value to encrypt, any type), a (int32: 1 deterministic, 2 randomized), and ki (the key id, a UUID) or ka (the key alternate name, a string); one of ki and ka is required |
01 | AEAD_AES_CBC_HMAC_SHA512 deterministic ciphertext | 16 bytes: the key UUID (the _id of the key used); 1 byte: the original BSON type; the ciphertext (the IV is prepended) |
02 | AEAD_AES_CBC_HMAC_SHA512 randomized ciphertext | the same as 01 |
The original BSON type is stored unencrypted so that a server-side JSON schema can check the type
of what was encrypted. The two documents differ on one point: the BSON Binary Encrypted
specification ends the ciphertext layout with the ciphertext itself, while the Client Side
Encryption appendix shows a uint32 ciphertext_length before it. Neither document
describes the blob subtypes of Queryable Encryption.
Binary subtype 7: compressed BSON column
Sources, all read 2026-11-13 from the MongoDB server repository (branch master):
src/mongo/bson/column/README.md, bsoncolumn.h,
bsoncolumn.cpp, bsoncolumn_util.h, bsonobj_traversal.h,
simple8b.h, simple8b_helpers.h and simple8b_type_util.cpp/.h.
There is no column specification in the mongodb/specifications repository (its listing was
checked), and the detailed format document that the README points to (a Google Docs
document, “BSON Column Compression”) was not opened; everything below is what
the public source implements. The server code is licensed SSPL; this page records
facts of the format, not code.
Overview
- The binary data of a subtype 7 value is a sequence of blocks that decode to the elements of an array (the implied field names
"0","1"… are not stored), followed by one00byte (EOO) that must be the last byte. Some elements may be missing (the decoder returns an EOO element for them). - Each block starts with a control byte. There are three kinds: an uncompressed literal, a run of Simple-8b words, and the start of interleaved mode.
- A literal is a whole BSON element with an empty field name: type byte,
00, value. A control byte is a literal control when(control & 0xE0) == 0(so a BSON type byte from01to13;00is the final EOO) or it isFF(min key) or7F(max key). - A literal sets the previous value. Later Simple-8b blocks hold deltas from it, so a series of same-type values compresses to the first value in full and small integers after.
Control bytes
| Control byte | Meaning |
|---|---|
00 | End of the column (EOO). Must be the last byte of the binary. |
01–13, 7F, FF | Uncompressed literal: the BSON element follows, field name empty. |
80, 90, A0, B0, C0, D0 (high nibble 8 to D) plus a low nibble | Simple-8b run. The low nibble plus one is the number of 8-byte little-endian Simple-8b words that follow (1 to 16). The high nibble is the scale index: 9 = 0 (multiplier 1), A = 1 (×10), B = 2 (×100), C = 3 (×10000), D = 4 (×100000000), 8 = 5 (“memory as integer”: the raw bits). Only doubles use scale indexes 0 to 4; every other type must use 8. For 128-bit types only 8 is valid. |
F0 | Start of interleaved mode, legacy form: arrays inside the objects are treated as scalar leaves (objects are traversed). |
F1 | Start of interleaved mode with traversal into arrays as well as objects; root is an object. |
F2 | Interleaved mode, root is an array (arrays are traversed). |
14–1F | Literal controls by the bit test (control & E0 is 0), but no BSON type has these codes. |
20–7E, E0–EF, F3–FE | Invalid; the decoder reports an error (no valid scale index). |
Simple-8b words
A word is 64 bits, little-endian. The low 4 bits are the selector; selector 0 is invalid. Value slots are packed from the low bits upward after the selector (and after the 4 extension bits for extended selectors). A slot whose bits are all ones is a skip (a missing value); all-ones is therefore not available as a value.
| Selector | Slots | Bits per slot |
|---|---|---|
| 1 | 60 | 1 |
| 2 | 30 | 2 |
| 3 | 20 | 3 |
| 4 | 15 | 4 |
| 5 | 12 | 5 |
| 6 | 10 | 6 |
| 7 (extension 0) | 8 | 7 |
| 8 (extension 0) | 7 | 8 |
| 9 | 6 | 10 |
| 10 | 5 | 12 |
| 11 | 4 | 15 |
| 12 | 3 | 20 |
| 13 | 2 | 30 |
| 14 | 1 | 60 |
| 15 | Run-length: the 4 bits after the selector hold n; it repeats the previous value (the last value decoded, even from an earlier word or control block) (n + 1) × 120 times (120 to 1920). | |
Extended selectors 7 and 8. For selector 7 or 8 the 4 bits after the selector are an extension that picks a finer layout; 0 means the plain layout above. In extended layouts each slot carries a trailing-zero count in its low bits and the value above it; the decoded number is value << (count × multiplier). The slot width is the value bits plus the count bits, and the value region of the word is 56 bits.
| Selector | Extension | Slots | Value bits | Count bits | Multiplier | Slot width |
|---|---|---|---|---|---|---|
| 7 | 1–9 | 9, 8, 7, 6, 5, 4, 3, 2, 1 | 2, 3, 4, 5, 7, 10, 14, 24, 52 | 4 | 1 | 6, 7, 8, 9, 11, 14, 18, 28, 56 |
| 8 | 1–7 | 7, 6, 5, 4, 3, 2, 1 | 4, 5, 7, 10, 14, 24, 52 | 4 | 4 (a nibble per unit) | 8, 9, 11, 14, 18, 28, 56 |
| 8 | 8–13 | 6, 5, 4, 3, 2, 1 | 4, 6, 9, 13, 23, 51 | 5 | 4 | 9, 11, 14, 18, 28, 56 |
| 7 | 10–15 | invalid (the decoder reports an invalid extended selector) | ||||
| 8 | 14–15 | invalid | ||||
The lists in each row are in order of extension number: selector 7 extension 1 has 9 slots of 2 value bits, extension 9 has 1 slot of 52 value bits; selector 8 extension 1 has 7 slots of 4 value bits, extension 7 has 1 slot of 52, extension 8 has 6 slots of 4 value bits and a 5-bit count, extension 13 has 1 slot of 51. A slot is a skip when its whole width (count bits included) is all ones. Values for 64-bit streams are read into 64 bits (the shift is taken modulo 64); 128-bit streams use 128-bit integers. The extension mechanism exists because deltas of 128-bit values (strings, binary, Decimal128) that would not fit in 60 bits often do when their trailing zero nibbles or bits are dropped.
Delta decoding
- A delta from a Simple-8b slot is first zigzag-decoded:
(v >> 1) ^ -(v & 1); the encoder moves the sign to bit 0 ((x << 1) ^ (x >> 63), or>> 127for 128-bit). Arithmetic wraps around on overflow. - Delta: new value = previous value + decoded delta. A zero delta repeats the previous element unchanged.
- Delta of delta (used by ObjectId, date and timestamp only): the decoded number is added to a running delta, and the running delta is added to the running value. After a literal the running delta is 0 and the running value is the literal's value.
- If there is no previous literal (the first thing in the column is a Simple-8b run), every slot is read as missing.
| Type | Stream | How the value maps to an integer |
|---|---|---|
int32 (10), int64 (12), boolean (08) | 64-bit, delta | The number itself (boolean 0 or 1). |
UTC datetime (09), timestamp (11) | 64-bit, delta of delta | The 8-byte integer (milliseconds; the timestamp's uint64). |
ObjectId (07) | 64-bit, delta of delta | The 12 bytes minus the 5-byte process-unique part (which is taken from the literal), rearranged into 7 bytes, low byte first: counter byte 2, timestamp byte 3, counter byte 1, timestamp byte 2, counter byte 0, timestamp byte 1, timestamp byte 0 (indices as stored in the ObjectId; timestamp and counter are big-endian). This puts the changing bytes in the low end. |
double (01) | 64-bit, delta | Scale index 0 to 4: the double multiplied by 1, 10, 100, 10000 or 100000000 and rounded to an integer; usable only if that is within ±253 and dividing back gives the exact bit pattern (so -0.0 and 0.0 differ). Scale index 5: the raw IEEE 754 bits as an integer. When a Simple-8b run follows a double, the previous value is re-scaled by that run's scale index; decoded value = integer / multiplier. |
Decimal128 (13) | 128-bit, delta | The 16 bytes as a little-endian 128-bit integer (low 64 bits then high 64 bits). |
string (02), JavaScript code (0D) | 128-bit, delta | Up to 16 bytes, reversed so that the last character (where most change is expected) is least significant, then read as a little-endian 128-bit integer. The string must not start with a NUL byte (a leading zero would make the length ambiguous); an empty string is 0. Decoding takes the 16 bytes, drops trailing zero bytes to find the length, and reverses; the value is written as the 4-byte length including NUL, the bytes, and a NUL. |
binary (05) | 128-bit, delta | Up to 16 data bytes as a little-endian 128-bit integer, zero padded. The decoded element keeps the length and the subtype of the previous element (the decoder copies those 5 bytes from it), and the previous element's data length must not exceed 16. |
| regex, DBPointer, code with scope, symbol, embedded document, array, null, undefined, min key, max key | zero delta only | Only a Simple-8b run of zeros (repeats of the previous literal) is valid; any other delta is an error (“invalid delta in 64-bit encoding”). |
Strings longer than 16 bytes, strings starting with NUL and binary data longer than 16 bytes cannot be turned into a 128-bit delta (the helper functions return no value for them, and the decoder uses 0 as the previous-value seed for such a literal). How the encoder stores them (presumably as literals) is in bsoncolumnbuilder.cpp, which was not read for this page.
Interleaved mode
- Control byte
F0,F1orF2is followed by a complete reference object, a normal BSON document (length, elements,00). It is not itself an element of the column. It holds a superset of the paths found in the objects of the sequence, in order, with the first value of each scalar field. - The reference object is traversed in document order; each scalar (non-object, and with
F1/F2non-array) field found becomes a stream with its own decoder state, seeded from that field's value. At least one scalar is required. - After the reference object come Simple-8b runs and literals for the streams, interleaved in the order in which the streams finish words: no stream tags are stored, the reader derives the order because the number of values in each word is known. A literal or control byte read when a stream's words are exhausted belongs to the stream that is needed next, in traversal order.
- To build each object, the decoder walks the reference schema in order, takes the next value of each stream, and writes it with the field name from the reference object; a skip makes that field absent (an object with no fields at all is a missing top-level element, an empty sub-object is allowed only if it was empty in the reference). A literal read inside a stream carries an empty name; the reference object supplies the name.
- The interleaved block ends when the first stream (the first scalar) is exhausted and the next control byte is
00; that byte is consumed, all other streams must be exhausted, and regular mode resumes with the following control byte. At least one object must be present. - Starting a new interleaved sequence ends the old one; the builder starts a new one when an object is incompatible with the current reference object.
ObjectId
12 bytes: a 4-byte big-endian timestamp (unsigned seconds since the Unix epoch), a
5-byte random value generated once per process and unique to the machine and process,
and a 3-byte big-endian counter that starts from a random value and wraps from
FFFFFF to 000000. Originally the random value was a machine
ID and a process ID; the ObjectID specification does not give their sizes.
Extended JSON
From the MongoDB Extended JSON specification (mongodb/specifications, extended-json.md,
read 2026-11-13). Extended JSON is a JSON text format for BSON, designed mainly for testing and human
inspection, with two formats: Canonical (type preserving) and Relaxed
(readable, type information lost for numbers and dates). A type wrapper object is a JSON object with
$-prefixed keys. Keys in canonical wrappers should be emitted in the order shown.
| BSON type | Canonical | Relaxed |
|---|---|---|
| ObjectId | {"$oid": "<24 hex digits>"} | same |
| Symbol | {"$symbol": "..."} | same |
| String | JSON string | same |
| Int32 | {"$numberInt": "42"} (the value as a string) | JSON integer |
| Int64 | {"$numberLong": "42"} | JSON integer |
| Double, finite | {"$numberDouble": "42.42"} (decimal string) | JSON non-integer number |
| Double, non-finite | {"$numberDouble": "Infinity"}, "-Infinity" or "NaN" (all NaNs) | same as canonical |
| Decimal128 | {"$numberDecimal": "1234.5"}, using the Decimal128 string rules | same |
| Binary | {"$binary": {"base64": "...", "subType": "04"}} (padded base64; subtype as a one- or two-character hex string) | same |
| Code | {"$code": "..."} | same |
| Code with scope | {"$code": "...", "$scope": {...}} | same |
| Document, Array | JSON object (with extensions), JSON array | same |
| Timestamp | {"$timestamp": {"t": 42, "i": 1}} (non-negative integers) | same |
| Regular expression | {"$regularExpression": {"pattern": "foo*", "options": "ix"}}; options in alphabetical order, or "" | same |
| DBPointer | {"$dbPointer": {"$ref": "<namespace>", "$id": {"$oid": "..."}}} | same |
| Datetime, year 1970 to 9999 | {"$date": {"$numberLong": "<ms since epoch>"}} | {"$date": "<RFC 3339 string>"} with at most millisecond precision; fractional seconds have exactly 3 decimal places when non-zero and are omitted when zero |
| Datetime, before 1970 or after 9999 | as above ($numberLong) | same as canonical |
| DBRef (a convention, not a type) | {"$ref": "collection", "$id": <Extended JSON of the id>}, with "$db" after $id when a non-empty database is supported; other fields come after | same |
| MinKey, MaxKey | {"$minKey": 1}, {"$maxKey": 1} | same |
| Undefined | {"$undefined": true} | same |
| Boolean, null | true/false, null | same |
- Parsers must accept both formats by default (legacy formats only if configured); should support at least 200 nesting levels; generators should support at least 100. Key order in an object is not significant. If an object has any of a type's special keys, it must have exactly that type's keys (else an error), except DBRef, which if incomplete (for example
$refwithout$id) is left as-is; matching keys with a wrongly typed value is an error; an unknown$key is left as it is (no error). - JSON numbers in Relaxed input: a non-integer is a double; an integer becomes the smallest BSON integer type that holds it, and if it cannot be held exactly as an integer, a double (never a string).
- UUIDs: binary subtypes 3 and 4 use the Binary form; additionally
{"$uuid": "c8edabc3-f738-4ca3-b68d-ab92a91478a3"}is accepted and is subtype 4; parsers must accept it without the URN prefix and may accept it without hyphens. (The example binaryyO2rw/c4TKO2jauSqRR4ow==with subtype04is the same UUID.) - Generators must offer both formats and should default to Relaxed; names
canonicalExtendedJSON,relaxedExtendedJSONand (if supported)legacyExtendedJSON; emit keys in BSON document order; may error on language types with no BSON equivalent. - Limits: JSON objects are unordered while BSON objects are ordered, and there is no escape for a leading
$in a document key, so the format is not designed to round-trip and should not be used where$-prefixed keys can occur (apart from DBRef). The compliance tests are in the BSON Corpus Test Suite, version 2.0 and above.
Example
16 00 00 00 document length 22
02 68 65 6C 6C 6F 00 type string, name "hello"
06 00 00 00 77 6F 72 6C 64 00 length 6, "world" and NUL
00 end of document