Bird
Raised Fist0
MongoDBquery~20 mins

How MongoDB indexes work (B-tree mental model) - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB B-tree Index Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
How does a B-tree index improve query speed in MongoDB?

Imagine you have a phone book sorted by last names. How does MongoDB's B-tree index help find a specific last name faster compared to scanning every entry?

AIt organizes data in a tree structure allowing quick jumps to the right section instead of checking every entry.
BIt stores all data in a single list and searches linearly from start to end.
CIt duplicates the entire collection to speed up queries.
DIt randomly picks entries until it finds the match.
Attempts:
2 left
💡 Hint

Think about how a dictionary helps you find words quickly by jumping to the right letter section.

❓ query_result
intermediate
2:00remaining
What is the output count of documents matched using an indexed field?

Given a MongoDB collection users with an index on age, what will be the count result of this query?

db.users.find({ age: { $gt: 30 } }).count()

Assume the collection has 100 documents with ages ranging from 1 to 100.

A30
B0
C100
D70
Attempts:
2 left
💡 Hint

Count how many ages are greater than 30 in the range 1 to 100.

📝 Syntax
advanced
2:00remaining
Which MongoDB index creation command is syntactically correct for a compound B-tree index?

Choose the correct command to create a compound index on lastName ascending and age descending fields.

Adb.collection.createIndex([lastName: 1, age: -1])
Bdb.collection.createIndex({ lastName: 1, age: -1 })
Cdb.collection.createIndex({ lastName => 1, age => -1 })
Ddb.collection.createIndex({ lastName: 'asc', age: 'desc' })
Attempts:
2 left
💡 Hint

Remember MongoDB uses JSON-like objects with field names and 1 or -1 for ascending/descending.

❓ optimization
advanced
2:00remaining
Which index choice optimizes queries filtering by both category and price fields?

You often query a products collection filtering by category and price. Which index will speed up these queries best?

AA text index on category and price
BSeparate single-field indexes on category and price
CA compound index on { category: 1, price: 1 }
DNo index, just scan the collection
Attempts:
2 left
💡 Hint

Think about how a single index can cover multiple fields in order.

🔧 Debug
expert
2:00remaining
Why does this MongoDB query not use the index as expected?

Given an index on username, why does this query not use the index?

db.users.find({ username: { $regex: 'admin' } })
ABecause the regex is a string pattern and MongoDB cannot use indexes with regex queries unless they are simple prefixes.
BBecause regex queries with anchors (^) always ignore indexes in MongoDB.
CBecause the regex is case sensitive and the index is case insensitive.
DBecause regex with ^ can use the index, so this query should use it.
Attempts:
2 left
💡 Hint

Consider how MongoDB uses indexes with regex patterns.

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