skip to content

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

level: middleimportance: nice to knowfreq 12%

answer

  1. two strings, no length prefix
  2. options in alphabetical order
  3. eight bytes, two 32-bit halves
  4. which half comes first on the wire?

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.

solid answer

~40 s

A Regex, type code `\x0B`, has no length prefix: it is the pattern as a `cstring`, then the options as a second `cstring`, so `abc` with options `im` takes 4 + 3 = 7 bytes. Because they are cstrings, neither can contain a NUL, and drivers must refuse one. Options have to be stored in alphabetical order; a decoder should still read unsorted options, while an encoder must emit sorted ones. A Timestamp, code `\x11`, is a fixed 8-byte `uint64`, little-endian, so the first 4 bytes on the wire are the increment and the last 4 are the seconds. Extended JSON's `$timestamp` lists `t` first, the reverse of the byte order.

code

json · 2 lines
json
{"a": {"$regularExpression": {"pattern": "abc", "options": "imx"}}}
{"a": {"$timestamp": {"t": 123456789, "i": 42}}}

go deeper

for a junior

Recall the shapes: a Regex is two null-terminated strings, and a Timestamp is 8 bytes split into two 32-bit parts.

for a middle

Predict the bytes for a sample value, recount the document length aloud, and read a Timestamp from a hex dump with the increment first.

for a senior

Explain the visible consequences: a round trip can change regex option bytes, and docs that describe bit significance can look like they contradict docs that describe wire order.

for a principal

Little here is a decision. The useful habit is requiring parsers and tooling to be tested against the published corpus vectors rather than against a reading of the prose.

## Regex: two cstrings The grammar for a BSON regular expression is `signed_byte(11) e_name cstring cstring`. The first `cstring` is the **pattern** and the second is the **options**. Three things follow from that. - **There is no length prefix.** A reader finds the end by scanning for two NUL bytes. This is unlike a string, whose `int32` says how long it is. - **Neither part can contain a NUL.** A `cstring` ends at its first NUL, so one inside a pattern would truncate it. The corpus lists a NUL in the pattern or the flags as a decode error, and its prose tests say drivers must refuse to encode either one. - **Empty parts still cost a byte.** An empty pattern with no options takes 2 bytes, both of them NUL. The value's size is the pattern's length plus the options' length plus 2. Here is the corpus vector for pattern `abc` with options `im`: ```plaintext 0F 00 00 00 document length: 15 0B type code: regular expression 61 00 key "a" as a cstring 61 62 63 00 pattern "abc" and its NUL 69 6D 00 options "im" and their NUL 00 document terminator ``` The sum is 4 + 1 + 2 + 4 + 3 + 1 = 15. ## Sorted options The specification says option characters **must be stored in alphabetical order**. It lists `i` for case-insensitive, `m` for multiline, `s` for dotall, `x` for verbose and `u` for Unicode-aware `\w`-style matching. The rule is split between the two directions: 1. An **encoder** must emit sorted options. Given `mix`, it writes `imx`. 2. A **decoder** must still read unsorted options. The corpus calls `mix` a degenerate form: parseable, but not compliant. 3. A **round trip** through a conforming driver produces the sorted form, so the bytes can change while the regex does not. The specification does not give a reason, but the effect is plain: a regex with the same pattern and options has one encoding, so equal values have equal bytes. In MongoDB 9.0, `validate` with `checkBSONConformance: true` flags unsorted options as non-conformant, and it accepts the option letters `ilmsux`, one more than the specification lists. ## Timestamp: one uint64, two halves The grammar is `signed_byte(17) e_name uint64`, and the value is always **8 bytes**. The specification describes it as an **increment** in the first 4 bytes and a **timestamp** in the second 4, and the manual gives that timestamp as seconds since the Unix epoch. BSON's basic types are little-endian, so the first 4 bytes on the wire are also the low half of the `uint64`: ```plaintext 10 00 00 00 document length: 16 11 type code: Timestamp 61 00 key "a" as a cstring 2A 00 00 00 increment: 42 15 CD 5B 07 seconds: 0x075BCD15 = 123456789 00 document terminator ``` The sum is 4 + 1 + 2 + 8 + 1 = 16. Three traps sit here: - **Wire order against reading order.** The manual describes the most significant 32 bits as the time and the least significant as the ordinal. That is the same fact as the specification's, seen from the number and not the bytes, yet it reads as the reverse. - **Extended JSON's order.** The corpus writes this value as `{"$timestamp": {"t": 123456789, "i": 42}}`, seconds first, the opposite of the bytes. - **Both halves are unsigned.** The corpus accepts `t` and `i` of 4294967295, the largest 32-bit value. A comment in the 9.0 server's `bsontypes.h` calls them two signed integers, but the grammar's `uint64` and the corpus say otherwise. ## The two side by side | | Regex | Timestamp | |---|---|---| | Type code | `\x0B` | `\x11` | | Size | Varies: both lengths plus 2 | Always 8 | | Length prefix | None | None, the size is fixed | | Inner order | Pattern, then options | Increment, then seconds | | Rule to remember | Options sorted, no NUL | Little-endian, unsigned | A reader can step over a Timestamp in one move, but it has to scan through a Regex. How a Timestamp is meant to be used, and how it differs from the Date type in practice, is a separate question about the database and not about the layout.

  • Can you store any regular expression your language supports in a BSON Regex?
    Not if the pattern contains a NUL byte, because a `cstring` ends at its first NUL. Drivers must refuse to encode such a pattern. Option letters outside the specification's list are a further risk: the format stores them as characters, but readers may reject them, and the server's conformance check flags letters outside its own set.
  • Why is the Timestamp's increment first in the bytes?
    The value is a little-endian `uint64`, so its least significant half is written first, and that half is the increment. Viewed as a number, the seconds occupy the most significant 32 bits, so comparing two values as `uint64` orders by seconds first and then by increment.

  • A BSON Regex starts with an int32 length, as a string does.
  • A Regex pattern may contain a NUL byte because it is stored as a string value.
  • Regex options keep the order the application wrote them in.
  • A Timestamp's first four bytes on the wire hold the seconds.
  • A BSON Timestamp's seconds and increment are signed 32-bit values.

Assumes MongoDB 9.0 for the conformance check's regex rules; both layouts themselves come from the BSON 1.1 specification and corpus.