MongoDB, on disk

MongoDB keeps every collection and every index in a B-tree file written by WiredTiger, its storage engine: documents as BSON keyed by a record ID, index keys in a byte-comparable form, a catalog that ties them together, and a journal of what came since the last checkpoint. Every example here is read from the sample, a data directory written by MongoDB 8.3.17.

The data directory

A node's dbPath holds a collection-*.wt file for each collection and an index-*.wt file for each index, named by an "ident" (in MongoDB 8, a UUID). Around them are WiredTiger's own files: WiredTiger.wt, the metadata table with every file's configuration and checkpoints; WiredTiger.turtle, a small text file that says where the metadata's own checkpoint is; WiredTigerHS.wt, the history store of older versions; and journal/, the write-ahead log. MongoDB adds _mdb_catalog.wt, which maps each namespace to its idents, and sizeStorer.wt, with document counts. The sample's music database has 60 artists, 200 albums and 1,559 tracks, the catalogue the other engines' samples hold, in 30 tables.

How a file is found

Opening the directory follows a chain. The turtle file names the metadata table's checkpoint; that checkpoint's root page leads to the metadata's entries, one per file, each with the file's configuration (key and value formats, compressor, page sizes) and its own checkpoint. The sample's metadata checkpoint is WiredTigerCheckpoint.2. A checkpoint is written as a hex string, an "address cookie": a version byte, then the root page's offset, size and checksum, then the same for the lists of allocated, free and discarded blocks, all as packed integers.

WiredTiger files: blocks and pages

A file is a sequence of blocks in units of 4 KB. The first unit is a descriptor: the magic number 120897, a version and a checksum. Every other block is a page: a 28-byte page header, a 12-byte block header, then cells. Internal pages list their children, each with the smallest key below it; leaf pages hold keys and values. The tracks table is 1 internal page over 2 leaf pages. The first leaf, at byte 49,152, starts:

OffsetPartBytes
0record number (column stores only): 000 00 00 00 00 00 00 00
8write generation: 606 00 00 00 00 00 00 00
16size in memory, decompressed: 118,653 bytes7d cf 01 00
20cells: 1,5963c 06 00 00
24page type 7: row leaf07
25flags: compressed, no empty values05
26unused, then the page format version00 01
28block: size on disk, 16,384 bytes00 40 00 00
32block: CRC-32Ce0 02 54 53
36block flags: the checksum covers the whole block01 00 00 00
40the first cells (kept uncompressed up to byte 64)05 81 80 c0 14 94 00 00 00 02 5f 69 64 00 04 00 00 00 31 2d 30 00 10 61

Numbers in the headers are little-endian. A page's address in its parent repeats its checksum, so a page written in the wrong place, or an old page, is caught even if its own checksum is right.

Cells and packed integers

A cell starts with a descriptor byte. A key or value under 64 bytes keeps its length in that byte, and its two low bits say which kind it is; longer ones have a type in the high four bits and a length after. A value cell may carry a time window: the transaction IDs and timestamps between which it is visible, how WiredTiger keeps snapshot reads correct once data is on disk. A key may also start with a count of bytes it shares with the key before it (prefix compression, which MongoDB turns on for indexes). Lengths, addresses and MongoDB's record IDs are WiredTiger's packed integers, which keep small numbers small and sort in numeric order: 1 is 81, 61 is bd, 200 is c0 88, 100000 is e3 01 66 60.

Compression

A page is compressed as a whole, except its first 64 bytes, which stay readable (the headers, and the first cells). Snappy is the default; a collection can choose zstd or zlib when it is created, and the sample's three collections each use a different one. The collections hold different data, so the ratios say as much about the data as about the compressors; small pages of short, varied documents compress least.

CollectionCompressorPagesUncompressedCompressedRatioFile
music.artistssnappy2 pages5.8 KB5.4 KB1.1×36.0 KB
music.albumszstd2 pages75.4 KB12.4 KB6.1×52.0 KB
music.trackszlib3 pages228.9 KB35.9 KB6.4×92.0 KB

Snappy and zstd pages store the compressed length first, in 8 bytes; zlib's stream knows its own end. Each page is padded to a whole number of 4 KB units, which is why a file is larger than its compressed pages.

Documents: BSON by record ID

A collection's table maps a record ID, a 64-bit number MongoDB assigns in insertion order, to the document's BSON. The record ID is not the _id: an index on _id maps one to the other, and a document keeps its record ID when it is updated. BSON is a binary JSON: a length, then elements, each a type byte, the field name and the value, then a 0 byte. Artist 6, 125 bytes at record ID 6:

OffsetPartBytes
0length: 125 bytes7d 00 00 00
4_id: int (type 16)10 5f 69 64 00 06 00 00 00
13name: string (type 2)02 6e 61 6d 65 00 09 00 00 00 41 72 74 69 73 74 20 36 00
32country: string (type 2)02 63 6f 75 6e 74 72 79 00 03 00 00 00 47 42 00
48genre: string (type 2)02 67 65 6e 72 65 00 05 00 00 00 6a 61 7a 7a 00
64formed: int (type 16)10 66 6f 72 6d 65 64 00 a4 07 00 00
76members: array (type 4), a document of its elements04 6d 65 6d 62 65 72 73 00 27 00 00 00 02 30 00 0a 00 00 00 4d 65 6d 62 …
89members.0: string (type 2)02 30 00 0a 00 00 00 4d 65 6d 62 65 72 20 36 61 00
106members.1: string (type 2)02 31 00 0a 00 00 00 4d 65 6d 62 65 72 20 36 62 00
124end of document00

An array is stored as a document whose field names are "0", "1" and so on. Numbers are little-endian. BSON has types JSON lacks: 32- and 64-bit integers, 128-bit decimals, dates, ObjectIds, binary data, regular expressions and timestamps.

Index keys: KeyString

An index's table is sorted by its keys' bytes, so MongoDB writes keys in a form that sorts as BSON values compare: KeyString. Each value becomes a type byte, ordered by BSON's type order, and an encoding that sorts by bytes: numbers by magnitude in as few bytes as they need, strings ending in a 0 byte, dates with the sign bit flipped. A descending field has every byte inverted. The key ends with 04, then the record ID it points to. The first key of the albums index on {year: -1, title: 1}:

OffsetPartBytes
0year, descending: every byte inverted: positive 2-byte integer part, 2019d3 f0 39
3title: string, 'Album 119'3c 41 6c 62 75 6d 20 31 31 39 00
14end of key04
15record ID 11903 b8

Since 1, NumberLong(1) and 1.0 compare equal, they get the same key; a few "type bits" in the value say which it was, so that the key can be turned back into the original value. The _id index is different: its key is only the value, which keeps it unique, and the record ID is in the value: the first is 64 65 a1 b2 c3 d4 e5 f6 00 00 00 00 01 04 → 00 08, record ID 1. An index on an array field is multikey: one entry per element, 267 entries for 200 albums in the sample's index on tags.

The catalog

_mdb_catalog.wt is a table of BSON documents, one per collection: its namespace, its options, the specification and state of each index, and the idents of its tables. The albums entry begins:

{
  md: {
    ns: 'music.albums',
    options: {
      uuid: UUID('f419e6fc-164f-4c89-9e2a-e828390bc001'),
      storageEngine: {
        wiredTiger: {
          configString: 'block_compressor=zstd'
        }
      }
    },
    indexes: [
      {
        spec: {
          v: 2,
          key: {
            _id: 1
          },
          name: '_id_'
        },
        ready: true,
        multikey: false,
        multikeyPaths: {
          _id: Binary.createFromBase64('AA==', 0)
        }
      },
  …

Checkpoints and the journal

WiredTiger never overwrites a page in place: a changed page is written to a free block, and a checkpoint (every 60 seconds by default) writes a new root and records it in the metadata, making a consistent version of every file. Between checkpoints, every committed write goes to the journal, WiredTiger's log: records aligned to 128 bytes, each with a CRC-32C and, if large, snappy-compressed, holding a transaction's operations: a put, remove or modify of a key in a table named by its file ID. A modify logs only the changed bytes: the sample's last change to album 1, a new price, is logged as 16 bytes written at offset 80 of its BSON: the 16-byte Decimal128.

On startup, recovery reads the turtle file, then replays the journal from the position the last checkpoint names: the metadata first, then each table, skipping what that table's own checkpoint already has. The sample's node was killed 5 transactions after its last checkpoint: 12 operations on collections and indexes that exist only in the journal. MongoDB preallocates journal files at 100 MB; the sample's keeps only the part that was written.

Reading it back

The viewer does all of this in the browser: it follows the turtle file to the metadata and the catalog, opens each table at its checkpoint, checks every page's checksum and decompresses it, decodes every cell, document and index key, and replays the journal. On the sample, every document and index key it reads matches what MongoDB returns, both from the checkpoint alone and after recovery.