How a MongoDB index works
· createIndex builds a B-tree; find walks it page by page/signatures/mongodb-indexbuilt on B-tree> use shop
switched to db shop
> db.users.insertMany([ /* 20 documents inserted */ ])
{ acknowledged: true, insertedCount: 20 }> db.users.createIndex({ age: 1 })building… 1 pages
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 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.