Bird
Raised Fist0
MongoDBquery~10 mins

How MongoDB indexes work (B-tree mental model) - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - How MongoDB indexes work (B-tree mental model)
Start: Query for value
↓
Check root node keys
↓
Compare query value with keys
↓
Go to child node based on range
↓
Repeat check keys in child node
↓
Reach leaf node with pointers to documents
↓
Return matching documents
↓
End
The query starts at the root node of the B-tree, compares the value with keys to decide which child node to follow, repeats this until reaching a leaf node that points to matching documents.
Execution Sample
MongoDB
db.collection.find({age: 30}).explain('executionStats')
This query searches for documents where the age is 30 using an index on the age field.
Execution Table
StepNode TypeKeys in NodeQuery Value ComparedDecisionNext Action
1Root[20, 40, 60]3030 > 20 and < 40Go to child node between 20 and 40
2Child[25, 35]3030 > 25 and < 35Go to child node between 25 and 35
3Leaf[28, 30, 33]30Found 30Return pointers to documents with age=30
4EndN/AN/AQuery completeReturn results to user
💡 Reached leaf node containing the key 30, so query returns matching documents.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Current NodeRootChild between 20 and 40Child between 25 and 35Leaf with keys [28,30,33]Leaf node reached
Query Value3030303030
DecisionN/AGo to child node between 20 and 40Go to child node between 25 and 35Found 30Return documents
Key Moments - 2 Insights
Why does the search start at the root node and not directly at the leaf?
The root node contains keys that help decide which child node to follow. This step-by-step narrowing down is how the B-tree efficiently finds the correct leaf node, as shown in steps 1 and 2 of the execution_table.
What happens if the query value is not found exactly in the keys?
The search still follows the child node whose key range would contain the value if it existed. Eventually, it reaches a leaf node where no exact match is found, and the query returns no results. This is implied by the decision steps in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at Step 2, which keys are in the child node?
A[25, 35]
B[20, 40, 60]
C[28, 30, 33]
D[30, 40, 50]
💡 Hint
Check the 'Keys in Node' column at Step 2 in the execution_table.
At which step does the query find the exact key matching the query value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Decision' column where it says 'Found 30'.
If the query value was 50 instead of 30, which child node would the root node direct the search to?
AChild node between 20 and 40
BChild node between 60 and above
CChild node between 40 and 60
DLeaf node directly
💡 Hint
Refer to Step 1's decision logic comparing query value with root keys.
Concept Snapshot
MongoDB indexes use a B-tree structure.
Queries start at the root node.
Keys in nodes guide which child node to follow.
Search continues down until leaf nodes.
Leaf nodes point to matching documents.
This makes searches fast and efficient.
Full Transcript
When MongoDB uses an index, it organizes keys in a B-tree structure. The search begins at the root node, which contains keys dividing the data ranges. The query value is compared with these keys to decide which child node to visit next. This process repeats, moving down the tree nodes, narrowing the search range. Eventually, the search reaches a leaf node that contains pointers to the actual documents matching the query. If the key is found, those documents are returned. If not, the query returns no results. This step-by-step traversal makes searching large datasets fast and efficient.

Practice

(1/5)
1. What is the main purpose of an index in MongoDB using a B-tree structure?
easy
A. To encrypt data for security
B. To store data in a compressed format
C. To speed up search and sort operations on data
D. To backup the database automatically

Solution

  1. Step 1: Understand what a B-tree index does

    A B-tree index organizes data so that searching and sorting can happen quickly.
  2. Step 2: Identify the main benefit of indexing

    Indexes help queries find data faster by avoiding full collection scans.
  3. Final Answer:

    To speed up search and sort operations on data -> Option C
  4. Quick Check:

    Index = Faster search and sort [OK]
Hint: Indexes speed up queries by organizing data [OK]
Common Mistakes:
  • Thinking indexes compress data
  • Confusing indexes with backups
  • Assuming indexes encrypt data
2. Which of the following is the correct syntax to create an ascending index on the field age in MongoDB?
easy
A. db.collection.createIndex({age: 1})
B. db.collection.createIndex(age: ascending)
C. db.collection.index({age: 'asc'})
D. db.collection.addIndex({age: 1})

Solution

  1. Step 1: Recall MongoDB index creation syntax

    The correct method is createIndex with a document specifying field and order.
  2. Step 2: Check the correct format for ascending order

    Ascending order is represented by 1, so {age: 1} is correct.
  3. Final Answer:

    db.collection.createIndex({age: 1}) -> Option A
  4. Quick Check:

    createIndex + {field: 1} = correct syntax [OK]
Hint: Use createIndex({field: 1}) for ascending index [OK]
Common Mistakes:
  • Using addIndex instead of createIndex
  • Passing string 'asc' instead of 1
  • Omitting curly braces around field
3. Given a collection with an index on score, what will be the order of documents returned by this query?
db.collection.find().sort({score: 1})
medium
A. Documents sorted by score in descending order
B. Documents sorted by insertion order
C. Documents in random order
D. Documents sorted by score in ascending order

Solution

  1. Step 1: Understand the sort parameter

    The sort({score: 1}) means sort by score ascending (lowest to highest).
  2. Step 2: Recognize index usage

    Since there is an index on score, MongoDB uses it to return documents in ascending order efficiently.
  3. Final Answer:

    Documents sorted by score in ascending order -> Option D
  4. Quick Check:

    sort({score: 1}) = ascending order [OK]
Hint: sort({field: 1}) means ascending order [OK]
Common Mistakes:
  • Confusing 1 with descending order
  • Assuming no order without explicit index
  • Thinking insertion order is default
4. You created a unique index on the field email but still see duplicate emails in your collection. What is the likely cause?
medium
A. The index was created with ascending order instead of unique
B. The unique index was created after duplicates existed
C. MongoDB does not enforce uniqueness on indexes
D. The field email is missing in some documents

Solution

  1. Step 1: Understand unique index behavior

    Unique indexes prevent duplicates only for new inserts after index creation.
  2. Step 2: Consider existing duplicates

    If duplicates existed before creating the unique index, MongoDB allows them unless you drop or clean data first.
  3. Final Answer:

    The unique index was created after duplicates existed -> Option B
  4. Quick Check:

    Unique index blocks new duplicates, not old ones [OK]
Hint: Unique index blocks new duplicates, not existing ones [OK]
Common Mistakes:
  • Thinking ascending order affects uniqueness
  • Believing MongoDB ignores unique constraints
  • Assuming missing fields cause duplicates
5. You want to optimize queries filtering by category and sorting by price. Which index is best to improve performance?
hard
A. A compound index on {category: 1, price: 1}
B. Two separate indexes: one on category, one on price
C. A unique index on price
D. No index needed if collection is small

Solution

  1. Step 1: Understand compound index benefits

    A compound index on {category: 1, price: 1} supports queries filtering by category and sorting by price efficiently.
  2. Step 2: Compare with separate indexes

    Separate indexes cannot optimize combined filter and sort as well as a compound index.
  3. Step 3: Consider uniqueness and collection size

    Unique index on price is irrelevant here; small collections may not need indexes but that is not optimization.
  4. Final Answer:

    A compound index on {category: 1, price: 1} -> Option A
  5. Quick Check:

    Compound index = best for filter + sort [OK]
Hint: Use compound index for filter and sort fields together [OK]
Common Mistakes:
  • Using separate indexes instead of compound
  • Confusing unique index with performance index
  • Ignoring index for small collections
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard