Home/Signatures/How a MongoDB index works
Search algorithmsCTRL K

How a MongoDB index works

· createIndex builds a B-tree; find walks it page by page
/signatures/mongodb-indexbuilt on B-tree
DOCUMENTS
20
in the users collection
INDEX PAGES
1h 1
B-tree nodes, height
PAGES READ
—
by the current query
KEYS EXAMINED
—
comparisons inside pages
DOCS EXAMINED
—
fetched through the index
page being readpages readmatchsplit halvesreceived a key
20 documents · order 4 · seed 7
step 0 / 27
Documents20
QUERIES
agefind({ age: 50 })
fromto
mongosh
> use shop
switched to db shop
> db.users.insertMany([ /* 20 documents inserted */ ])
{ acknowledged: true, insertedCount: 20 }
> db.users.createIndex({ age: 1 })
building… 1 pages
CURRENT STEP
createIndex

Collection users holds 20 documents and no index: find({ age: x }) has to read all 20 (COLLSCAN). Build the index on age: one B-tree key per document.

// how it works

How a MongoDB index works

A MongoDB index is a B-tree stored by the WiredTiger engine: each page holds sorted keys and pointers to the pages below, and every leaf sits at the same depth. createIndex inserts one key per document; find({ age: 31 }) starts at the root, compares the key with the few keys of the page, descends into one child, and reaches the leaf in as many page reads as the tree is tall.

Without the index the only plan is a COLLSCAN: read every document and test the predicate. explain('executionStats') shows the difference as totalKeysExamined and totalDocsExamined; the numbers on this page are exactly those. A range query descends once and then walks the leaves in order.

// b-tree

What to notice

The height barely moves as documents come in: a real index over millions of rows is only 3 or 4 pages tall.
A page split is the only expensive moment of an insert; MongoDB does it in the background too.
docs examined by the index equals the matches; a COLLSCAN examines all of them, always.
Open the algorithm page: B-treeTrees · Back to /trees/b-tree