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?
Think about how a dictionary helps you find words quickly by jumping to the right letter section.
A B-tree index splits data into sorted blocks, allowing MongoDB to jump directly to the block containing the searched value, avoiding scanning all entries.
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.
Count how many ages are greater than 30 in the range 1 to 100.
Ages from 31 to 100 inclusive are 70 numbers, so 70 documents match.
Choose the correct command to create a compound index on lastName ascending and age descending fields.
Remember MongoDB uses JSON-like objects with field names and 1 or -1 for ascending/descending.
The correct syntax uses an object with field names as keys and 1 or -1 as values to specify ascending or descending order.
category and price fields?You often query a products collection filtering by category and price. Which index will speed up these queries best?
Think about how a single index can cover multiple fields in order.
A compound index on both fields allows MongoDB to efficiently filter by category first, then price, improving query speed compared to separate indexes.
Given an index on username, why does this query not use the index?
db.users.find({ username: { $regex: 'admin' } })Consider how MongoDB uses indexes with regex patterns.
MongoDB can use indexes for regex queries only if the regex is a simple prefix expression like /^prefix/. The pattern 'admin' matches anywhere in the field value and cannot use the index.