Courseiva

CCNA Indexing Questions

48 questions · Indexing · All types, answers revealed

1
MCQmedium

When should a TTL (Time-To-Live) index be used in a MongoDB collection?

A.To keep data indefinitely.
B.To manage temporary or ephemeral data.
C.To speed up high-frequency write operations.
D.To ensure unique values in a field.
AnswerB

TTL indexes are perfect for data with a limited lifespan, such as user session data, audit logs, or temporary caches. The database automatically removes these documents once they reach their expiration time, reducing the need for manual cleanup and keeping the collection size manageable for the active data set.

Why this answer

TTL indexes are designed to automatically remove documents from a collection after a certain period of time or at a specific time. This is ideal for ephemeral data like session logs, cached items, or temporary alerts. By relying on the database engine to handle the deletion, developers avoid writing custom cleanup scripts, ensuring that data is purged consistently without impacting application logic or manual overhead on the system.

Exam trap

Candidates often select TTL indexes for precise, exact-time transactional data scheduling or permanent data archiving, confusing background automatic cleanup with deterministic job execution.

2
MCQeasy

When creating an index on a large collection in a production environment, what is the primary advantage of using the 'background' option (for versions prior to 4.2) or the standard build process in 4.2+?

A.The index build completes much faster than a foreground build.
B.The index will take up significantly less space on the disk.
C.It prevents the index build from blocking read and write operations on the collection.
D.It automatically creates the index on all secondaries in a single transaction.
AnswerC

The modern index build process is designed to be non-blocking. By allowing concurrent read and write operations, developers can create indexes on live production systems without causing downtime or significant latency spikes. This is a critical feature for managing large datasets that require new indexes as application requirements evolve.

Why this answer

In modern MongoDB (4.2+), all index builds use an optimized process that only holds an exclusive lock at the beginning and end of the operation, allowing the database to remain available for reads and writes. This prevents the index creation from blocking application traffic, which is essential for maintaining high availability and a good user experience during maintenance.

Exam trap

Candidates often think index creation locks the entire database indefinitely, missing that modern MongoDB versions use optimized background builds to maintain high availability.

3
MCQeasy

A developer needs to ensure that a `users` collection does not contain two documents with the same email address. Which index type should be created on the `email` field?

A.A sparse index
B.A partial index
C.A hashed index
D.A unique index
AnswerD

A unique index on the email field enforces that no two documents can have the same value for email. This prevents duplicate email addresses at the database level. MongoDB will reject inserts or updates that would violate the uniqueness constraint, ensuring data integrity. This is the standard way to enforce uniqueness on a field.

Why this answer

To prevent duplicate email addresses, a unique index on the email field is required. Unique indexes enforce that each value appears at most once. Other index types like sparse, partial, or hashed do not provide this guarantee.

A unique index is the correct choice to maintain data integrity for the email field.

Exam trap

The trap here is confusing sparse or partial indexes with unique indexes, thinking that any special index type can enforce uniqueness.

4
MCQeasy

A developer is working with a MongoDB collection that stores user profiles. The collection has an index on the `email` field. The developer runs a query to find a user by email and then examines the query plan using `explain()`. The output shows that the query used an `IXSCAN` stage. What does this indicate about the query execution?

A.The query returned all documents from the collection because the index was not selective.
B.The query used the index to sort the results but still had to scan the collection to filter documents.
C.The query used the index to find the matching documents without scanning the entire collection.
D.The query performed a collection scan because no suitable index was found.
AnswerC

An `IXSCAN` stage in the explain output indicates that MongoDB used an index scan to satisfy the query. This means the query leveraged the index on the `email` field to locate the matching documents efficiently, rather than scanning every document in the collection. This is generally the desired outcome for a query that filters on an indexed field, as it reduces the number of documents examined and improves performance.

Why this answer

The `IXSCAN` stage in the explain output signifies that MongoDB used an index scan to retrieve the documents matching the query. This is the expected behavior when querying on an indexed field like `email`. It means the query did not perform a full collection scan, which would be indicated by `COLLSCAN`.

Using an index allows MongoDB to efficiently locate the relevant documents, reducing the number of documents examined and improving query performance.

Exam trap

The trap here is confusing `IXSCAN` with `COLLSCAN` or assuming that `IXSCAN` implies a full collection scan, when in fact it indicates the use of an index.

5
MCQhard

What is the primary benefit of using a partial index in MongoDB?

A.It forces all documents to be indexed.
B.It reduces the index size and resource usage.
C.It prevents duplicates across the entire collection.
D.It is required for all compound indexes.
AnswerB

By limiting the indexed documents to a specific subset, partial indexes significantly reduce the overall size of the index. Smaller indexes occupy less RAM in the WiredTiger cache and consume less disk space, which directly leads to improved performance for write operations and faster overall query execution for specific subsets.

Why this answer

Partial indexes allow you to index only a subset of documents that meet a specific filter expression. This reduces the index size, resulting in lower memory and storage consumption. By ignoring unnecessary documents, the database avoids wasting resources on indexing data that is never or rarely queried.

This optimization is particularly beneficial for large collections where only a small percentage of data is active or frequently accessed, leading to significant performance gains.

Exam trap

Candidates often confuse partial indexes with sparse indexes, mistakenly believing partial indexes require the indexed field itself to be absent rather than evaluating an explicit filter expression.

6
MCQmedium

A developer maintains a collection of sensor readings. Queries almost always filter on `status` and then sort by `timestamp` descending. The current index is { status: 1, timestamp: 1 }. The developer observes that the query planner selects a COLLSCAN even though the index covers both fields. Which index change should be made to allow an efficient index scan for this query?

A.Add a separate index { timestamp: -1 } and keep the existing compound index.
B.Create a new index { status: 1, timestamp: -1 } and drop the existing index.
C.Create a new index { timestamp: -1, status: 1 } and drop the existing index.
D.Create a hashed index on `status` combined with `timestamp` to improve selectivity.
AnswerB

With equality on `status` and a descending sort on `timestamp`, the index must place the equality field first and the sort field in the matching direction. `{ status: 1, timestamp: -1 }` satisfies both, so the planner can perform an index scan that returns documents already ordered, avoiding a blocking sort and a collection scan.

Why this answer

The query combines an equality predicate on `status` with a descending sort on `timestamp`. Following equality-sort-range ordering, the equality field belongs first and the sort field must match the query direction, giving `{ status: 1, timestamp: -1 }`. That lets the planner walk the index in the requested order without a blocking sort, which is why the reversed or split alternatives fail.

Exam trap

The trap here is assuming any compound index containing both fields will work, when the field order and sort direction must exactly match the equality-then-sort pattern.

7
Multi-Selecthard

A developer is working with a MongoDB collection that stores user profiles. The collection has a unique index on `email` and a compound index on `{ lastName: 1, firstName: 1 }`. The developer needs to enforce that no two documents have the same combination of `tenantId` and `username`. Which TWO of the following statements are correct regarding the creation and behavior of a unique compound index for this requirement? (Choose two.)

Select 2 answers
A.Creating a unique compound index on `{ tenantId: 1, username: 1 }` enforces uniqueness across the combination of both fields, not on each field individually.
B.If the collection already contains duplicate `{ tenantId, username }` pairs, the unique index creation will fail unless duplicates are removed or the index is created with a partial filter expression.
C.The unique compound index will also enforce uniqueness on `tenantId` alone, because the first field of a compound index is treated as a separate unique key.
D.Creating the unique compound index requires the `collMod` command to be run first on the collection to enable unique constraints.
E.A unique compound index automatically becomes a sparse index, so documents missing either `tenantId` or `username` are excluded from the uniqueness constraint.
AnswersA, B

A unique compound index enforces that the combined values of the indexed fields are unique. It does not require each field to be unique on its own. In this scenario, the same `username` could appear under different `tenantId` values, and the same `tenantId` could appear with different `username` values, as long as the pair is unique.

Why this answer

A unique compound index on `{ tenantId: 1, username: 1 }` enforces uniqueness on the combination of both fields, not on either field alone. If existing duplicates are present, the index build will fail until they are resolved or excluded via a partial filter expression. The index is not sparse by default, does not enforce prefix uniqueness, and is created with `createIndex`, not `collMod`.

Exam trap

The trap here is assuming that a unique compound index makes each field individually unique or that it is automatically sparse, when it actually enforces uniqueness only on the full field combination.

8
MCQmedium

A logistics application stores shipment records in a collection where each document has a numeric field `weight_kg`. Queries frequently filter on `weight_kg` with a range (e.g., between 50 and 200) and sort by `weight_kg` ascending. You create a standard ascending index on `weight_kg`. Which statement best describes the index's behavior for these queries?

A.The index cannot be used for range queries on numeric fields because B-tree indexes are designed for equality matches only.
B.The index can support the range filter but cannot provide sorted results, so a blocking sort will be required.
C.The index will be used only if the range filter is selective enough; otherwise, MongoDB ignores it and performs a collection scan.
D.The index can efficiently serve both the range filter and the ascending sort, avoiding an in-memory sort.
AnswerD

A single-field ascending index on `weight_kg` maintains keys in ascending order. For a range query on that field and an ascending sort on the same field, MongoDB can traverse the index range in order, returning documents already sorted. This eliminates the need for a blocking sort and improves performance for such queries.

Why this answer

A single-field ascending index on a numeric field stores keys in sorted order. When a query filters on a range of that field and sorts ascending on the same field, MongoDB can scan the index range and return results in the requested order. This avoids an expensive blocking sort and leverages the index for both filtering and sorting, making it the optimal choice for such query patterns.

Exam trap

The trap here is assuming that an index used for filtering cannot also satisfy a sort on the same field, leading to unnecessary blocking sorts.

9
MCQeasy

A developer is working with a MongoDB collection that stores sensor readings. Each document has a 'sensorId' field and a 'readings' array containing numeric values. The developer creates an index on the 'readings' field. Which statement best describes the resulting index?

A.The index stores a single entry per document representing the entire array, similar to a composite value.
B.The index is a multikey index, and it contains an entry for each element in the readings array across all documents.
C.The index is a sparse index automatically, excluding documents where the readings array is empty.
D.The index cannot be created because indexing an array field is not supported in MongoDB.
AnswerB

When you index a field that contains an array, MongoDB automatically creates a multikey index. For each document, the index stores a separate entry for every element in the array, allowing queries that match individual array elements to use the index. This is the defining behavior of multikey indexes and is essential for efficient array queries.

Why this answer

Indexing a field that holds an array causes MongoDB to create a multikey index, which stores one index entry for each element of the array in every document. This enables efficient queries that match individual array elements. The other options incorrectly describe the index structure or claim unsupported behavior.

Understanding multikey indexes is fundamental for querying arrays efficiently.

Exam trap

The trap here is assuming that an array field is indexed as a single unit, when MongoDB actually creates multiple index keys per document for array elements.

10
MCQmedium

A retail application queries an `orders` collection with a filter on `status` and `customerId`, and a sort on `orderDate`. The query shape is: `db.orders.find({ status: "shipped", customerId: 12345 }).sort({ orderDate: -1 })`. The collection has no indexes other than the default `_id` index. Which index should be created to best support this query according to the ESR guideline?

A.{ status: 1, orderDate: -1, customerId: 1 }
B.{ status: 1, customerId: 1, orderDate: -1 }
C.{ customerId: 1, orderDate: -1, status: 1 }
D.{ orderDate: -1, status: 1, customerId: 1 }
AnswerB

The ESR guideline orders index fields as Equality, Sort, Range. Here `status` and `customerId` are equality predicates and `orderDate` is used for sorting. Placing the equality fields first and the sort field last allows the index to satisfy the equality matches and then provide sorted results without an in-memory sort, making this the optimal compound index.

Why this answer

The ESR guideline orders compound index fields as Equality, Sort, Range. The query has equality predicates on `status` and `customerId` and a sort on `orderDate`. Placing both equality fields first and the sort field last, as in `{ status: 1, customerId: 1, orderDate: -1 }`, lets the index serve the equality matches and provide sorted output without an in-memory sort.

Exam trap

The trap here is assuming that the sort field should come first because sorting is expensive, when the ESR guideline actually places equality fields before the sort field.

11
MCQmedium

A logistics application stores shipment records in a MongoDB collection where each document includes a 'status' field (e.g., 'pending', 'in_transit', 'delivered') and a 'createdAt' date. The operations team frequently runs the query: db.shipments.find({ status: 'in_transit' }).sort({ createdAt: -1 }).limit(20). They want an index that allows this query to execute without an in-memory sort and with minimal keys scanned. Which index should you create?

A.db.shipments.createIndex({ createdAt: -1, status: 1 })
B.db.shipments.createIndex({ createdAt: -1 }) with a partial filter on status
C.db.shipments.createIndex({ status: 1, createdAt: -1 })
D.db.shipments.createIndex({ status: 1 }) and rely on the sort in memory
AnswerC

This compound index matches the query's equality predicate on status and the sort on createdAt with a descending direction. Because the index stores entries in the exact order needed, MongoDB can walk the 'in_transit' portion and return documents already sorted, avoiding an in-memory SORT stage. It also limits scanned keys to roughly the first 20 matching entries, satisfying the limit efficiently.

Why this answer

The query has an equality predicate on status followed by a descending sort on createdAt. The ESR rule (Equality, Sort, Range) indicates that equality fields should precede sort fields in a compound index. Creating an index with status first and createdAt second in the matching sort direction allows MongoDB to seek directly to the in_transit entries and traverse them in already-sorted order, eliminating the blocking in-memory sort and minimizing scanned keys.

Exam trap

The trap here is assuming that any index containing both fields can satisfy the sort, when field order and sort direction in the compound index are what determine whether the sort is covered.

12
MCQhard

What is the primary technical limitation when creating a covered query?

A.The query must include the _id field.
B.All projected fields must be contained in the index.
C.The collection must be small.
D.Covered queries only work with single-field indexes.
AnswerB

For a query to be covered, the index must contain every field returned by the projection. If the projection includes any field that is not indexed, the engine must access the original document to retrieve that data, which defeats the purpose of the covered query and increases I/O overhead significantly.

Why this answer

A covered query occurs when all fields requested in the query are present in the index. This allows MongoDB to return the result set directly from the index without having to load the actual documents from disk. The primary limitation is that you must include only the indexed fields in your projection.

If even one field is not in the index, the database must perform an expensive 'fetch' operation to retrieve the full document from storage.

Exam trap

Candidates often assume that any query using an index is a covered query, forgetting that including unindexed fields in the projection forces a document fetch from disk.

13
MCQhard

A financial application has a collection `transactions` with fields `accountId`, `type`, `amount`, and `createdAt`. A query filters on `accountId` and `type`, sorts descending by `createdAt`, and projects only `_id` and `amount`. A developer creates the index `{ accountId: 1, type: 1, createdAt: -1 }`. Which statement best describes whether this index can support the query as a covered query?

A.It can be covered if the query uses `explain()` with the `covered` option, which forces MongoDB to answer from the index.
B.It can be covered only if the projection explicitly excludes `_id`, because the index does not contain the `_id` field.
C.It cannot be covered because the index lacks the `amount` field, so MongoDB must fetch documents to return `amount`.
D.It is automatically covered because `_id` is always included in every index, so all projected fields are present.
AnswerC

For a query to be covered, every field in the query filter, sort, and projection must be included in the index. The projection includes `amount`, but the index does not contain `amount`. Therefore MongoDB must read the full documents to retrieve `amount`, and the query is not covered. Adding `amount` to the index would make coverage possible.

Why this answer

A covered query requires that all fields used in the filter, sort, and projection exist in the index. Here the projected field `amount` is not part of the compound index, so MongoDB must fetch documents to return it. Neither excluding `_id` nor using `explain()` changes that; the index would need to include `amount`.

Exam trap

The trap here is believing that a query can be covered whenever the filter and sort match the index, forgetting that every projected field must also be present in the index.

14
Multi-Selecthard

A developer is working with a collection 'products' that has an index { category: 1, price: 1 }. They want to understand how MongoDB can use this index for queries that include a sort on price. Which TWO of the following statements are true regarding the use of this index for sorting? (Choose two.)

Select 2 answers
A.The index can support a sort on price descending even if the query does not include any condition on category, because the index stores price in descending order when traversed in reverse.
B.The index can support a sort on price descending if the query includes an equality condition on category, by scanning the index in reverse.
C.The index can support a sort on price ascending if the query includes an equality condition on category.
D.The index can support a sort on price ascending if the query includes a range condition on category, such as { category: { $gt: 'A' } }.
E.The index can support a sort on price ascending even if the query does not include any condition on category.
AnswersB, C

This is true because MongoDB can traverse an index in either direction. With an equality condition on category, the index entries for a given category are ordered by price ascending. To satisfy a sort on price descending, MongoDB can scan those entries in reverse order, avoiding an in-memory sort. This is a standard optimization.

Why this answer

The index { category: 1, price: 1 } can support sorting on price when the query includes an equality condition on category, because then the index's price entries are contiguous and sorted. It can also support a descending sort by scanning the index in reverse. Without an equality condition on category, the index cannot provide a global sort on price because the leading field category varies.

Exam trap

The trap here is assuming that a compound index can always provide a sort on any suffix field regardless of the predicates on the prefix fields.

15
MCQmedium

A collection 'orders' has a compound index { status: 1, customerId: 1, orderDate: -1 }. A developer runs a query: db.orders.find({ customerId: 'C123', status: 'shipped' }).sort({ orderDate: -1 }). Which statement about how MongoDB uses this index for the query is correct?

A.The index can be used for the equality filter on status and customerId, and it can also provide the sort on orderDate in descending order without an in-memory sort.
B.The index cannot be used for this query because the query includes a sort on a field that is not the first field of the index.
C.The index can be used for the equality filter on status and customerId, but the sort on orderDate will require an in-memory sort because the index stores orderDate in ascending order only.
D.The index can be used for both the equality filter on status and customerId, but it cannot provide the sort order on orderDate because the sort field is not contiguous with the equality fields.
AnswerA

This is correct. The compound index prefix is { status: 1, customerId: 1 }, and both fields have equality conditions in the query. The third index field is orderDate: -1, and the query sorts by orderDate: -1. Since the equality fields are fixed to single values, the remaining index portion is ordered by orderDate descending, so MongoDB can use the index to return sorted results directly.

Why this answer

The compound index begins with status and customerId, both of which have equality conditions in the query. Since those fields are fixed, the index's remaining field orderDate is effectively ordered by its index direction. The query sorts by orderDate descending, matching the index direction, so MongoDB can use the index to satisfy both the filter and the sort without an in-memory sort stage.

Exam trap

The trap here is assuming that a sort field must be the first field of the index or that it cannot be used when equality conditions exist on preceding fields.

16
MCQmedium

You are optimizing a collection containing user logs. Queries frequently filter by 'category' and sort by 'timestamp' in descending order. Which index configuration best supports these queries while maintaining efficiency?

A.{ category: 1 }
B.{ timestamp: -1, category: 1 }
C.{ category: 1, timestamp: -1 }
D.{ timestamp: -1 }
AnswerC

Following the ESR rule, this index places the equality field first and the sort field second. This structure allows MongoDB to jump directly to the category and use the pre-sorted order of the index to return the timestamped results, avoiding costly in-memory sorting operations during query execution.

Why this answer

The ESR rule suggests placing Equality fields before Sort fields. By indexing { category: 1, timestamp: -1 }, MongoDB can filter by category and then traverse the index in the order specified for sorting. This eliminates the need for an in-memory sort stage, which is crucial for performance as the result set grows.

Efficient index usage directly reduces memory consumption and prevents expensive blocking operations on the primary node.

Exam trap

Candidates often violate the ESR rule by putting the sort field before the equality field in compound indexes, triggering costly in-memory sorts.

17
MCQeasy

What is the primary function of the explain() method in MongoDB?

A.To automatically optimize the query for faster execution.
B.To provide diagnostic information about query execution.
C.To delete inefficient indexes from the collection.
D.To force the query to use a specific index.
AnswerB

The explain() method returns a document containing the execution plan, including index usage, stage information, and performance statistics. This data is critical for developers and administrators to analyze how the MongoDB query planner decided to execute the operation and whether it utilized the optimal index for the request.

Why this answer

The explain() method provides detailed information about how a query is executed, including which index was used, the number of documents scanned, and the time taken for the operation. It is the essential diagnostic tool for database administrators to identify performance bottlenecks, verify that queries are using the intended indexes, and optimize slow-running queries by examining the execution plan and resource usage statistics provided by the database engine.

Exam trap

Candidates often think explain() is used for performance tuning by modifying the query, rather than recognizing it purely as a diagnostic tool for viewing execution plans.

18
MCQmedium

You need to ensure that values in the 'email' field are unique across all documents in a collection, but documents where the 'email' field is missing should not violate this constraint. How should you create this index?

A.Create a standard unique index on the email field
B.Create a sparse index on the email field without uniqueness
C.Create a wildcard index on the email field
D.Create a unique partial index with a filter expression requiring email to exist
AnswerD

A partial index applies the uniqueness constraint only to documents matching its filter expression, so requiring the email field to exist excludes documents lacking it. This satisfies the constraint that missing-email documents must not trigger duplicate key violations.

Why this answer

Partial indexes allow you to restrict the indexing operation to a subset of documents that meet a specified filter expression. By combining a unique constraint with a partial filter expression requiring the field to exist, you prevent duplicate values for present fields while allowing multiple documents to omit the field entirely.

Exam trap

Candidates often try to use a standard unique index, which fails because it treats missing fields as null, causing conflicts if multiple documents lack the email field.

19
MCQeasy

Which index type should be used to support efficient queries on a field containing geographical coordinates in MongoDB?

A.Text index
B.Hashed index
C.2dsphere index
D.Compound index
AnswerC

The 2dsphere index supports queries that interpret data as points on an earth-like sphere. It is the primary index type for geolocation data, enabling operations like $nearSphere, $geoWithin, and $geoIntersects, which are necessary for calculating distances and boundaries between various geographic coordinates efficiently.

Why this answer

The 2dsphere index is specifically designed to support queries on geospatial data using spherical geometry. This index type is essential for location-based applications that perform proximity searches or geometry intersections. By structuring data this way, MongoDB can optimize calculations for distances between points on a sphere, which is crucial for modern mapping and delivery applications that require high precision and performance over large datasets.

Exam trap

Candidates often confuse 2d indexes with 2dsphere indexes, failing to realize that 2dsphere is required for accurate spherical calculations on Earth-based coordinate data.

20
MCQmedium

A logistics company stores shipment events in a collection where each document contains a `history` array of subdocuments with fields `status`, `timestamp`, and `location`. Queries frequently filter on `history.status` and sort by `history.timestamp`. An index is created on `history.status`. What is the most accurate statement about this index?

A.The index is multikey; each element of the `history` array produces a separate index key, and querying `history.status` can use the index.
B.The index is sparse by default because array fields often contain missing values, so it excludes documents where `history.status` is absent.
C.The index stores one key per document, using the first element of the `history` array, so only queries matching the first event can use it.
D.The index cannot be created because MongoDB does not allow indexing a field that contains an array of subdocuments.
AnswerA

MongoDB automatically creates a multikey index when the indexed field contains an array. Each array element generates a distinct index entry, so a query on `history.status` can match the appropriate entries. The index does not store the full array as a single value, but it still supports equality and range predicates on the array field.

Why this answer

When an indexed field contains an array, MongoDB builds a multikey index and creates an index key for each array element. This allows queries that filter on `history.status` to use the index efficiently. The index is not restricted to the first element, it is not sparse by default, and creating it is fully supported.

Exam trap

The trap here is assuming that indexing an array field is unsupported or that only one array element is indexed, when MongoDB actually creates a multikey index with one key per element.

21
MCQhard

You are optimizing a query: db.orders.find({ status: 'urgent', amount: { $gt: 500 } }).sort({ order_date: -1 }). According to the ESR (Equality, Sort, Range) rule, what is the ideal index for this query?

A.{ amount: 1, order_date: -1, status: 1 }
B.{ order_date: -1, status: 1, amount: 1 }
C.{ status: 1, order_date: -1, amount: 1 }
D.{ status: 1, amount: 1, order_date: -1 }
AnswerC

This follows the ESR rule perfectly. 'status' is an equality match, 'order_date' is the sort field, and 'amount' is a range filter. By ordering them this way, MongoDB can filter by status, then use the index's natural order for the sort, and finally apply the range filter on the remaining entries.

Why this answer

The ESR rule is a best practice for ordering fields in a compound index to maximize efficiency. Equality matches should come first to narrow the result set, followed by the Sort field to allow the index to provide the requested order, and finally the Range filter. This order minimizes the number of index keys scanned and avoids in-memory sorts.

Exam trap

Candidates often place the range filter field before the sort field, which prevents the index from being used to satisfy the sort, leading to slow in-memory sorting operations.

22
MCQhard

You are managing a MongoDB collection that stores sensor data. Each document has a `timestamp` field and a `sensorId` field. The collection is very large, and you need to optimize a query that finds the most recent reading for a specific sensor. The query is: `db.sensors.find({ sensorId: 'abc123' }).sort({ timestamp: -1 }).limit(1)`. Which index would best support this query?

A.db.sensors.createIndex({ sensorId: 1, timestamp: -1 })
B.db.sensors.createIndex({ timestamp: -1, sensorId: 1 })
C.db.sensors.createIndex({ sensorId: 1, timestamp: 1 })
D.db.sensors.createIndex({ timestamp: 1, sensorId: 1 })
AnswerA

This index is optimal because it follows the ESR rule. The query has an equality condition on `sensorId` and a sort on `timestamp` descending. Placing `sensorId` first allows MongoDB to quickly narrow down to the specific sensor, and then the index entries for that sensor are sorted by `timestamp` descending. This means the query can retrieve the first index entry for that sensor and immediately return the most recent reading without scanning or sorting.

Why this answer

The query filters on `sensorId` (equality) and sorts by `timestamp` descending. To optimize, the index should follow the ESR rule: equality field first, then sort field. The index must also match the sort direction.

Therefore, an index on `{ sensorId: 1, timestamp: -1 }` allows MongoDB to quickly find the specific sensor and then retrieve the most recent timestamp from the index without scanning or sorting. This is the most efficient index for this query pattern.

Exam trap

The trap here is overlooking the sort direction and assuming that any index with the correct fields in the correct order will work, when in fact the sort direction must also align.

23
Multi-Selectmedium

You are designing indexes for a MongoDB collection that stores user profiles. The collection has a field 'email' that must be unique, and a field 'username' that is also unique. You also need to support queries that find users by a combination of 'country' and 'city'. Which TWO of the following statements are correct regarding index creation and behavior in this scenario? (Choose two.)

Select 2 answers
A.Creating a unique index on email will prevent insertion of documents with duplicate email values, but will allow multiple documents with missing email field only if the index is sparse or partial.
B.A compound index on { country: 1, city: 1 } can support queries that filter on city alone, because MongoDB can use the index prefix from the right side.
C.A compound index on { country: 1, city: 1 } can be used for a query that filters on both country and city, and also for a query that filters on country alone.
D.Creating a unique index on username will automatically create a unique index on email if both are specified in the same createIndex command using a compound key pattern.
E.Unique indexes in MongoDB enforce uniqueness across all fields in the document, not just the indexed field, to prevent duplicate documents.
AnswersA, C

A unique index enforces uniqueness on the indexed field, but by default it treats missing fields as null and allows only one document without the field. To allow multiple documents missing the email field while still enforcing uniqueness when present, you must create the index with the sparse option or a partial filter expression. This is a common requirement for optional unique fields.

Why this answer

The scenario requires unique constraints on email and username, and query support for country and city. A unique index on email allows multiple missing emails only if sparse or partial, so that statement is correct. A compound index on country and city supports queries on the leading field country and on both fields together, making that statement correct.

The other statements misstate index prefix behavior, compound uniqueness, or the scope of unique indexes.

Exam trap

The trap here is confusing compound index prefix support with the ability to use any field, and misunderstanding that a compound unique index enforces uniqueness on the combination, not on each field separately.

24
MCQhard

What is the primary consequence of having too many indexes on a collection that experiences a high volume of write operations?

A.Increased disk space usage for data storage.
B.Decreased performance of write operations.
C.Increased memory usage for query execution.
D.Improved speed for data deletion operations.
AnswerB

Write performance suffers because each index must be updated synchronously during document modifications. As the count of indexes grows, the number of operations per write increases, creating a bottleneck that slows down the ingestion of data and negatively impacts the overall latency of the application's write-intensive processes.

Why this answer

Every index on a collection must be updated whenever a document is inserted, updated, or deleted. In write-heavy workloads, this results in significant write amplification. Each write operation triggers multiple index update tasks, consuming CPU and I/O resources.

Maintaining excessive indexes leads to performance degradation as the system struggles to keep all indexes synchronized with the base data, directly impacting latency and throughput for application-level database interactions.

Exam trap

Candidates often think extra indexes only consume disk space, failing to realize the significant performance tax on write operations caused by constant index updates (write amplification).

25
MCQmedium

A developer is working with a MongoDB collection that has a partial index defined as `db.products.createIndex({ price: 1 }, { partialFilterExpression: { price: { $gt: 100 } } })`. The developer runs a query `db.products.find({ price: { $lt: 50 } })`. Which of the following statements describes how MongoDB will execute this query?

A.MongoDB will use the partial index to find documents with price less than 50.
B.MongoDB will use the partial index but will filter out documents that do not match the query predicate.
C.MongoDB will perform a collection scan to find documents with price less than 50.
D.MongoDB will return an error because the query cannot be satisfied by the partial index.
AnswerC

MongoDB will perform a collection scan because the partial index is not applicable to the query. The partial index only includes documents where `price > 100`, and the query is for `price < 50`. Since the query predicate does not overlap with the partial filter expression, the index cannot be used. MongoDB will fall back to a collection scan to find the matching documents, examining every document in the collection. This is less efficient but necessary because no suitable index exists for this query.

Why this answer

A partial index only includes a subset of documents in a collection based on a filter expression. In this case, the partial index only contains documents where `price > 100`. The query filters for `price < 50`, which does not overlap with the partial filter expression.

Therefore, the index cannot be used to satisfy the query. MongoDB will perform a collection scan to find the matching documents. It will not use the partial index, nor will it return an error; it will simply choose an alternative execution plan.

Exam trap

The trap here is assuming that a partial index can be used for any query on the indexed field, when in fact it can only be used if the query predicate is covered by or overlaps with the partial filter expression.

26
MCQmedium

A MongoDB collection contains documents with a field `tags` that is an array of strings. A developer creates an index on the `tags` field. Which of the following statements is true about the resulting index?

A.The index will only include the first element of the array to save space.
B.The index will contain one entry for each element in the array, and it is called a multikey index.
C.The index will be a sparse index by default because arrays can be empty.
D.The index will contain one entry per document, using the entire array as the key.
AnswerB

When you index a field that holds an array, MongoDB automatically creates a multikey index. Each element of the array gets its own index entry, enabling efficient equality and range queries on array elements. This is the correct behavior for indexing an array field like tags.

Why this answer

When you create an index on a field that contains an array, MongoDB automatically creates a multikey index. This index has separate entries for each element of the array, allowing efficient queries on individual array elements. It is not sparse by default, and it does not index only the first element.

This behavior is fundamental to querying arrays in MongoDB.

Exam trap

The trap here is thinking that an array is indexed as a single value, but MongoDB creates a multikey index with an entry per array element.

27
MCQmedium

Which property of a Multikey Index is true when indexing an array field?

A.A document can only have one index entry in a multikey index.
B.Multikey indexes cannot index array fields.
C.It creates an index entry for each element in the array.
D.Multikey indexes are created manually by the user.
AnswerC

Multikey indexes function by expanding array elements into individual index entries. This mechanism allows MongoDB to quickly query documents based on the presence of specific values inside the array, which is essential for working with data structures like tags, categories, or user roles stored as arrays in documents.

Why this answer

A Multikey Index is automatically created when an index is placed on a field containing an array. The index creates an entry for each element in the array, effectively mapping the index key to the parent document. This allows queries to efficiently find documents that contain specific values within their arrays.

However, it also means that a single document can have multiple entries in the index, which is a key technical distinction.

Exam trap

Candidates often incorrectly assume that a Multikey Index creates a single index entry per array or that it cannot index arrays of objects, leading to confusion about index size.

28
MCQmedium

You are designing a schema for a social media platform where users have an array of 'tags' and an array of 'mentions'. You attempt to create an index on { tags: 1, mentions: 1 }. What is the most likely outcome of this operation?

A.The index is created successfully and supports queries that filter by both tags and mentions.
B.The index build fails with an error stating that a compound index cannot include more than one array.
C.The index is created but only the first element of each array is indexed to save space.
D.The index is created but it will only be used if the query provides a specific index hint.
AnswerB

A compound index can only contain one field that is an array to maintain a manageable index size. If you try to index two different array fields in one compound index, MongoDB returns an error to prevent the explosive growth of index entries that would occur from mapping every possible combination of elements.

Why this answer

MongoDB restricts multikey indexes such that a single compound index cannot cover more than one array field. This limitation prevents the index from growing exponentially in size, which would happen if it had to create a cartesian product of every element in both arrays. Developers must choose which array is more critical for query performance or use alternative indexing strategies.

Exam trap

Candidates often assume MongoDB supports compound indexes with multiple array fields, forgetting that a single compound index cannot contain more than one array because it would require an exponential cartesian product.

29
MCQmedium

Your application executes the query: db.users.find({ age: { $gt: 30 } }, { age: 1, _id: 0 }). You have an index on { age: 1 }. How does MongoDB process this query?

A.MongoDB performs an index scan followed by a fetch to get the 'age' values.
B.This is a covered query, and MongoDB retrieves all data from the index alone.
C.MongoDB must fetch the documents because projections are not supported in covered queries.
D.The query cannot be covered because the _id field is always required from the document.
AnswerB

The query is considered 'covered' because the index on { age: 1 } contains the 'age' field used in the filter, and the projection only asks for 'age' while excluding '_id'. By satisfying the query without accessing the actual documents, MongoDB reduces disk I/O and speeds up the response time significantly.

Why this answer

A covered query occurs when the index contains all the fields required by both the query filter and the projection. Because the query only requests the 'age' field and explicitly excludes '_id', MongoDB can fulfill the entire request by looking only at the index. This avoids the need to fetch documents from the heap, significantly improving performance.

Exam trap

Candidates often forget that the '_id' field is included in documents by default; if the query does not explicitly exclude it, the index cannot cover the query.

30
MCQhard

A developer is working with a collection that has a compound index on { a: 1, b: 1, c: 1 }. They run a query that includes a filter on `a` and a sort on `c`. The query is: `db.collection.find({ a: 5 }).sort({ c: 1 })`. Which of the following best describes how MongoDB will execute this query?

A.The query will use the index to both filter on `a` and sort by `c`, avoiding an in-memory sort.
B.The query will use the index to filter on `a` and then sort the results in memory by `c`.
C.The query will use a covered index scan because all fields are in the index.
D.The query will not use the index at all and will perform a collection scan.
AnswerB

The index { a: 1, b: 1, c: 1 } can be used to efficiently filter on `a` because `a` is the leading field. However, the sort on `c` cannot be satisfied by the index alone because `b` is between `a` and `c` in the index. MongoDB will need to perform an in-memory sort on `c` after retrieving the documents. This is the correct behavior.

Why this answer

With a compound index { a: 1, b: 1, c: 1 }, an equality filter on `a` can use the index efficiently. However, a sort on `c` cannot be satisfied by the index because `b` intervenes. MongoDB must perform an in-memory sort on the filtered results.

The index is still used for filtering, but it does not avoid the sort stage.

Exam trap

The trap here is assuming that any field in a compound index can be used for sorting if the equality field is first, but the sort field must be contiguous after the equality fields.

31
MCQmedium

A developer wants to implement full-text search on a collection of articles. They create a text index on the 'content' field. Which of the following is a significant limitation of 'text' indexes in MongoDB?

A.Text indexes do not support case-insensitive searches.
B.A collection can have at most one 'text' index.
C.Text indexes cannot be used in a sharded cluster.
D.You cannot use 'text' indexes with the $match operator in aggregation.
AnswerB

MongoDB restricts each collection to a single text index. To search across multiple fields, you must include all those fields in a single compound text index. This design ensures that the $text operator has a single, unambiguous index to use when executing full-text search queries.

Why this answer

A collection in MongoDB can have at most one text index. However, this single index can cover multiple fields by creating a compound text index. This limitation means developers must carefully plan which fields need to be searchable via text commands and consolidate them into a single index definition for that collection.

Exam trap

Test-takers often assume multiple text indexes can be created on different fields across a single collection to handle separate search requirements.

32
MCQhard

A financial analytics collection stores documents with fields 'accountId' (string), 'transactionDate' (date), and 'amount' (decimal). A common query is: db.transactions.find({ accountId: 'A123', transactionDate: { $gte: ISODate('2024-01-01'), $lte: ISODate('2024-01-31') }, amount: { $gt: 1000 } }). You need an index that supports this query efficiently. Following the ESR rule, which index key pattern is optimal?

A.{ accountId: 1, amount: 1 } and a separate index on transactionDate
B.{ accountId: 1, transactionDate: 1, amount: 1 }
C.{ transactionDate: 1, accountId: 1, amount: 1 }
D.{ accountId: 1, amount: 1, transactionDate: 1 }
AnswerB

The query has an equality on accountId, a range on transactionDate, and a range on amount. With no sort specified, the ESR rule places the equality field first, then the range fields. Ordering transactionDate before amount allows the index to seek to the account and then scan the date range; amount is evaluated as an index filter on the remaining entries. This minimizes keys examined and avoids a full collection scan.

Why this answer

The query contains an equality on accountId and range predicates on transactionDate and amount, with no explicit sort. The ESR rule dictates that equality fields come first, then sort fields (none here), then range fields. Placing the equality field accountId first allows a direct seek, and ordering the range fields transactionDate then amount lets the index scan the date range efficiently while filtering amount as a residual index condition.

This reduces keys examined and avoids a collection scan.

Exam trap

The trap here is assuming that the order of range fields does not matter, when in fact placing the equality field first and choosing a sensible range order affects how many index keys are scanned.

33
MCQeasy

You are considering using a hashed index for a 'product_id' field to distribute data across shards. Which of the following is a known limitation of hashed indexes in MongoDB?

A.Hashed indexes do not support equality matches, only range queries.
B.Hashed indexes can only be created on fields that contain unique values.
C.Hashed indexes do not support range-based queries or sort operations.
D.Hashed indexes are only available in the MongoDB Enterprise Edition.
AnswerC

Because hashing transforms values into a pseudo-random distribution, the original order of the data is lost. A query for values greater than 100 cannot use a hashed index because the hash of 101 might be numerically smaller or larger than the hash of 1000, making the B-tree structure useless for ranges.

Why this answer

Hashed indexes compute a hash of the value of a field and use that hash to create the index. While this is great for equality matches and even distribution in sharding, it destroys the natural ordering of the data. Consequently, hashed indexes cannot support range-based queries (like greater than or less than) or sorting operations.

Exam trap

Many test-takers confuse hashed indexes with standard indexes, mistakenly believing they support range queries or sorting because they distribute data evenly across shards for equality lookups.

34
MCQmedium

Refer to the exhibit. If a query is executed as db.collection.find({ "metadata.type": "book" }), how will MongoDB use the created index?

A.The index will be used to quickly find all documents where 'type' is 'book'.
B.MongoDB will perform a collection scan because the index is on the whole object.
C.The index will be used, but performance will be slower than a dot-notation index.
D.The index build will fail because metadata is a nested document.
AnswerB

By indexing 'metadata', you are indexing the full BSON subdocument. Queries on sub-fields like 'metadata.type' are not supported by this index. For the index to be useful for the given query, it should have been created on the specific path 'metadata.type' using dot notation in the createIndex command.

Why this answer

Indexing a whole subdocument (the 'metadata' field) creates an index on the literal BSON object. This index is only useful for exact matches of the entire subdocument, including field order. It cannot be used to look up individual fields within that subdocument using dot notation.

To index internal fields, you must use the dot notation in the index definition itself.

Exam trap

Candidates assume indexing a subdocument object allows querying its inner fields via dot notation, forgetting that the index matches the literal object structure.

35
MCQeasy

A team stores user profiles in a `profiles` collection. About 90% of documents have a `deletedAt` field set to null, and only 10% have an actual timestamp indicating soft deletion. Queries that list active users filter on `deletedAt: null` and sort by `createdAt`. The team wants an index that stays small and avoids maintaining entries for deleted documents. Which index definition best matches this requirement?

A.db.profiles.createIndex({ createdAt: 1 }, { partialFilterExpression: { deletedAt: null } })
B.db.profiles.createIndex({ createdAt: 1 }, { expireAfterSeconds: 0 })
C.db.profiles.createIndex({ deletedAt: 1 }, { sparse: true })
D.db.profiles.createIndex({ deletedAt: 1, createdAt: 1 })
AnswerA

A partial index with `partialFilterExpression: { deletedAt: null }` only stores entries for active documents, roughly 10% of the collection. It supports the equality filter on `deletedAt: null` and the sort on `createdAt`, while dramatically reducing index size and write overhead compared to indexing every document.

Why this answer

A partial index limits entries to documents matching its filter expression. Filtering on `deletedAt: null` stores only active profiles, so the index is far smaller than a full compound or sparse index and still supports the equality-plus-sort query. Sparse indexes are unsuitable because the field exists with a null value rather than being absent.

Exam trap

The trap here is reaching for a sparse index to exclude documents, when sparse only skips missing fields and ignores documents whose field is present but null.

36
Multi-Selectmedium

Which TWO of the following statements regarding the ESR rule for index creation are true?

Select 2 answers
A.Equality fields should be placed after range fields.
B.Equality fields should be placed before sort fields.
C.Sort fields should be placed before range fields.
D.The ESR rule is only applicable to single-field indexes.
E.Range fields should always be placed at the beginning of an index.
AnswersB, C

Following the ESR rule, equality fields must come first to restrict the document set as much as possible before moving to sorting. This ensures that the engine processes the smallest number of documents for the sort operation, which is highly resource-intensive and benefits from reduced input sizes.

Why this answer

The ESR rule stands for Equality, Sort, and Range, providing a standard guideline for ordering fields in a compound index to maximize performance. By placing equality fields first, the query engine narrows down the search space immediately. Sorting fields come next to satisfy the query's order requirements without blocking, and range fields are placed last to allow the index to effectively filter remaining documents using the index prefix.

Exam trap

Candidates often get the ESR order wrong by placing range fields before sort fields, which prevents the index from efficiently supporting the sort operation without an in-memory sort.

37
MCQmedium

You are storing GPS coordinates in a 'locations' collection using GeoJSON format. You need to perform queries that find points within a specific polygon. Which index type must be created on the location field?

A.A '2d' index, as it is the standard for all geospatial data.
B.A '2dsphere' index to support GeoJSON and spherical geometry.
C.A standard ascending index, as GeoJSON is just a nested document.
D.A 'geo' index, which automatically chooses between 2d and 2dsphere.
AnswerB

The '2dsphere' index is specifically built for Earth-like spherical geometry. It supports GeoJSON points, line strings, and polygons. This index is necessary for executing queries that determine if a point exists within a geographical boundary (polygon) while accounting for the curvature of the Earth.

Why this answer

For querying data on a sphere (like the Earth), MongoDB provides the '2dsphere' index. This index type supports GeoJSON objects and calculates distances using spherical geometry. It is required for advanced geospatial queries such as $geoWithin or $nearSphere when working with real-world coordinates and complex shapes like polygons.

Exam trap

Students frequently confuse 2d and 2dsphere index types, mistakenly applying planar 2d indexes to spherical GeoJSON coordinate data.

38
MCQmedium

An IoT platform stores sensor readings in a collection `readings` with fields `deviceId`, `timestamp`, and `value`. The collection is large and grows continuously. Queries typically retrieve the most recent readings for a specific device, filtering by `deviceId` and sorting by `timestamp` descending. The operations team wants to minimize index size while still supporting these queries efficiently. Which index strategy best meets this requirement?

A.Create a hashed index on { deviceId: 1 } combined with a single-field index on { timestamp: -1 } to distribute data and support sorting.
B.Create a compound index on { deviceId: 1, timestamp: -1 } only, which supports the equality filter and the descending sort without an additional index.
C.Create a compound index on { deviceId: 1, timestamp: -1 } and a separate single-field index on { timestamp: -1 } to handle global sorts.
D.Create a single-field index on { deviceId: 1 } only, because the sort on `timestamp` can always be performed in memory efficiently.
AnswerB

A compound index on `{ deviceId: 1, timestamp: -1 }` matches the query pattern: equality on `deviceId` followed by a sort on `timestamp` descending. It allows MongoDB to locate the device's readings in sorted order directly from the index, avoiding an in-memory sort. No extra index is needed, which minimizes index size and maintenance.

Why this answer

The query pattern filters by `deviceId` and sorts by `timestamp` descending. A compound index on `{ deviceId: 1, timestamp: -1 }` directly supports both the equality match and the sort, allowing MongoDB to return results in order without an in-memory sort. This single index is sufficient, minimizing index size and avoiding unnecessary additional indexes.

Exam trap

The trap here is adding extra indexes such as a separate `timestamp` index or a hashed index, when a single well-ordered compound index already satisfies the equality filter and the sort.

39
MCQhard

An application queries a users collection with db.users.find({ email: "a@b.com" }). The collection holds about 2 million documents, and the email field is unique for every user. A developer proposes creating an index { email: 1, country: 1 } to speed up the query. What is the most accurate assessment of this proposal?

A.It works, but it is wasteful; a single-field index { email: 1 } on this unique field would give the same lookup efficiency with a smaller index.
B.It is invalid unless the index is declared as unique to match the field's uniqueness.
C.It is optimal because compound indexes always outperform single-field indexes on the leading field.
D.It fails because the query does not include the country field, so the compound index cannot be used.
AnswerA

The compound index can still serve the query because email is the leading field, so the planner can seek directly to the matching entry. However, since email is unique and the query filters only on email, the trailing country key is never used to narrow the scan. A single-field index { email: 1 } delivers identical lookup performance while consuming less space and adding less overhead to every write.

Why this answer

Because email is the leading field of the compound index, the planner can use it and seek directly to the single matching entry, so the query is still fast. But the trailing country key is never touched by this query, and email is already unique, so it adds no selectivity. A single-field index on email achieves the same lookup with less storage and lower write amplification.

Exam trap

The trap here is believing an index can only be used when the query includes every indexed field, or conversely that adding more fields always improves performance.

40
MCQmedium

A logistics application stores shipment records in a collection named `shipments`. Each document includes a `status` field (e.g., "in_transit", "delivered") and a `delivery_date` field. The development team frequently runs a query that filters on `status` and sorts by `delivery_date` in ascending order. They want to create a compound index to optimize this query. Which index should they create?

A.{ status: 1, delivery_date: 1 }
B.{ status: 1 }
C.{ delivery_date: 1, status: 1 }
D.{ status: 1, delivery_date: -1 }
AnswerA

This index places the equality-filtered field (status) first, followed by the sort field (delivery_date). MongoDB can use the index to directly match the status value and then retrieve results already sorted by delivery_date, avoiding an in-memory sort. This follows the Equality, Sort, Range (ESR) rule and is optimal for the given query pattern.

Why this answer

For a query that filters on one field and sorts on another, the index should list the equality-filtered field first, followed by the sort field. This allows MongoDB to use the index for both the filter and the sort, avoiding an expensive in-memory sort. The index { status: 1, delivery_date: 1 } matches this pattern and is optimal.

Exam trap

The trap here is assuming that the sort field should come first in the index, but the equality field must lead to allow efficient filtering and sorting.

41
MCQhard

An application writes documents to a `metrics` collection where each document contains an embedded array `samples` of subdocuments with fields `value` and `unit`. A query filters on `samples.unit` and `samples.value` together, expecting both conditions to match the same array element. The developer creates { "samples.unit": 1, "samples.value": 1 }. Which behavior should the developer expect from this index?

A.The index is automatically converted into a wildcard index covering all subdocument fields.
B.The index is valid and can be used, but it may return documents where `unit` and `value` match different array elements unless the filter is written carefully.
C.The index enforces that `unit` and `value` come from the same element, returning only matching pairs.
D.The index cannot be created because compound multikey indexes are disallowed on array fields.
AnswerB

A compound multikey index on paths within one array is legal and useful for narrowing candidates. However, the index cannot guarantee that the matched `unit` and `value` belong to the same subdocument. To enforce same-element semantics, the query must use `$elemMatch`, which the planner evaluates after fetching the document.

Why this answer

Compound multikey indexes are allowed when the indexed paths belong to the same array, so the index can be created and used to reduce the candidate set. The critical limitation is that the index does not preserve element pairing: a document can match `samples.unit` and `samples.value` from different elements. Using `$elemMatch` restores the same-element requirement during document filtering.

Exam trap

The trap here is believing that indexing multiple paths inside one array preserves subdocument pairing, when multikey indexes flatten keys and lose element identity.

42
MCQmedium

An e-commerce application frequently executes a query filtering by 'category' and 'brand', and then sorts the results by 'price' in ascending order. You created a compound index on { category: 1, brand: 1, price: 1 }. Which statement best describes how MongoDB utilizes this index for a query that filters only on 'brand' and 'price'?

A.The query engine will perform an index scan because 'brand' and 'price' are part of the index.
B.MongoDB will perform a collection scan as the query lacks the 'category' prefix required by the index.
C.The index will be used only for the sort operation on 'price' but not for the filter on 'brand'.
D.MongoDB will use the index to find 'brand' but will still need to fetch documents to verify 'price'.
AnswerB

The index prefix rule dictates that a query must use the first field of the compound index to enable an index scan. Because 'category' is omitted, the query engine cannot utilize the B-tree structure of the index for 'brand' and 'price', resulting in a full collection scan to find matching documents.

Why this answer

Compound indexes in MongoDB utilize a prefix-based matching system. To use an index for filtering or sorting, the query must include the first field of the index or a sequence of fields starting from the first. Since 'category' is the first field and is missing from the query filter, MongoDB cannot use this specific index for efficient lookups, highlighting the importance of field ordering in index design.

Exam trap

Candidates often mistakenly believe that an index on {a, b, c} can be used to query {b, c}, forgetting that the query must include the leading prefix of the index.

43
Multi-Selectmedium

A developer is tuning indexes on an `orders` collection. The team reports slow queries and heavy write latency, and they suspect too many indexes. Which TWO practices should the developer apply when reviewing the index set? (Choose two.)

Select 2 answers
A.Replace all single-field indexes with wildcard indexes to consolidate coverage.
B.Set the notablescan parameter to true so the server rejects unindexed queries.
C.Compare query patterns with existing indexes to confirm each index supports a real workload.
D.Use the $indexStats aggregation stage to identify indexes with low access counts.
E.Drop every compound index whose prefix duplicates another index to reduce write cost.
AnswersC, D

Mapping observed query shapes to the current index set reveals gaps and redundancies. An index that supports no measured query pattern is a removal candidate, while a missing index for a frequent shape is a creation candidate. This evidence-based review aligns index maintenance with actual workload rather than assumptions.

Why this answer

Reducing index bloat requires evidence. `$indexStats` shows which indexes are actually used, and comparing real query patterns against the existing index set confirms whether each index earns its keep. Together these two practices let the team drop unused indexes and keep only those that support measured workload, lowering write cost without sacrificing query performance.

Exam trap

The trap here is assuming any index with a redundant prefix or a broader wildcard can be safely removed or consolidated, when only observed usage and query patterns justify those decisions.

44
MCQmedium

You have a collection of user activity logs where queries frequently filter by `userId` and sort by `timestamp` in descending order. Which single index definition provides optimal support for this query pattern without requiring an in-memory sort?

A.{ userId: 1, timestamp: 1 }
B.{ timestamp: -1, userId: 1 }
C.{ userId: 1, timestamp: -1 }
D.{ userId: -1, timestamp: -1 }
AnswerC

A compound index on userId ascending then timestamp descending matches both the equality filter and the sort order, so MongoDB walks the index in the required descending sequence and returns results without an in-memory sort stage, satisfying the no-blocking-sort constraint.

Why this answer

To avoid an in-memory sort, the index direction must match the query's sort direction for the sorted fields. Since `userId` is filtered via equality and `timestamp` is sorted descending, the index `{ userId: 1, timestamp: -1 }` allows MongoDB to traverse the index naturally in the required order, ensuring optimal query performance and preventing sorting memory limit errors during execution.

Exam trap

Candidates often ignore the direction of the sort, assuming an index on {userId: 1, timestamp: 1} will work for a descending sort, which forces an expensive in-memory blocking sort.

45
MCQmedium

A collection 'logs' has a TTL index on the 'createdAt' field with expireAfterSeconds set to 3600. A developer notices that some documents older than one hour are still present in the collection. Which explanation is most likely?

A.The TTL index only deletes documents when they are queried, so unqueried documents remain indefinitely.
B.The TTL index only deletes documents when the MongoDB server is restarted.
C.The TTL index does not delete documents if the collection has a compound index that includes the createdAt field.
D.The TTL monitor runs every 60 seconds and may have not yet processed those documents, so they can remain for a short period beyond the expiration time.
AnswerD

This is correct because the TTL background thread runs approximately every 60 seconds. Documents are not deleted exactly at the expiration second; there can be a delay of up to a minute or more. Therefore, documents older than one hour might still be present if the TTL monitor has not run yet since they expired. This is expected behavior.

Why this answer

The TTL monitor is a background process that runs every 60 seconds to delete expired documents. Due to this interval, documents can remain for a short time after their expiration time. This is the most likely reason for seeing documents older than one hour still present in the collection.

Exam trap

The trap here is assuming that TTL deletion is instantaneous or that other indexes can block it.

46
MCQmedium

You are the lead developer for a high-traffic e-commerce application using MongoDB 6.0. A query on the `orders` collection that filters on `customerId` and sorts by `orderDate` in descending order is performing poorly. You decide to create an index to improve its performance. Which of the following indexes would be most efficient for this query?

A.db.orders.createIndex({ customerId: 1, orderDate: 1 })
B.db.orders.createIndex({ customerId: 1, orderDate: -1 })
C.db.orders.createIndex({ orderDate: -1, customerId: 1 })
D.db.orders.createIndex({ orderDate: 1, customerId: 1 })
AnswerB

This index is correct because it follows the Equality, Sort, Range (ESR) rule. The query has an equality condition on `customerId` and a sort on `orderDate`. Placing the equality field first and the sort field second allows MongoDB to use the index for both filtering and sorting, avoiding an in-memory sort. The sort order in the index matches the query's sort order, which is crucial for performance.

Why this answer

The most efficient index for a query with an equality filter and a sort is one that follows the Equality, Sort, Range (ESR) rule: equality fields first, then sort fields. The index must also match the sort direction. Here, the query filters on `customerId` (equality) and sorts by `orderDate` descending.

Therefore, an index on `{ customerId: 1, orderDate: -1 }` allows MongoDB to use the index for both filtering and sorting, avoiding an expensive in-memory sort and ensuring optimal performance.

Exam trap

The trap here is assuming that any index containing the queried fields will be used efficiently, without considering the order of fields and the sort direction relative to the query.

47
MCQmedium

A support team frequently runs a query that filters on status and sorts by created_at, both fields in the same collection. An existing index { status: 1 } is in place, but the query still performs an in-memory sort and gets killed once result sets grow past the 100 MB sort limit. Which index should you create to let the server satisfy both the filter and the sort without a blocking sort stage?

A.{ created_at: 1, status: 1 }
B.{ status: 1, created_at: -1 }
C.{ status: 1, created_at: 1 }
D.{ created_at: 1 }
AnswerC

With the equality field first and the sort field second, the index entries for a given status value are already ordered by created_at. The query engine can walk that range and return documents in sorted order, eliminating the blocking SORT stage entirely. This is the equality-sort pattern that keeps the query from ever hitting the 100 MB in-memory sort ceiling.

Why this answer

An index that lists the equality predicate field first and the sort field second stores entries for each status value in created_at order. The server can then read the matching range sequentially and emit results already sorted, which removes the blocking SORT stage and its 100 MB memory ceiling. Reversing the field order or flipping the sort direction prevents the index from supplying the required order.

Exam trap

The trap here is assuming any index containing both fields can satisfy the sort, when field order and sort direction inside the index determine whether a blocking sort is avoided.

48
MCQeasy

A developer is working with a collection that stores user profiles. The collection has an index on the `email` field. The developer runs a query that uses a regular expression to find all users whose email ends with "@example.com". The query is: `db.users.find({ email: /@example\.com$/ })`. What is the most likely behavior of this query with respect to the index?

A.The query will use the index but will still need to filter the results in memory.
B.The query will use the index efficiently because regular expressions can always leverage indexes.
C.The query will use the index only if the field is a covered index.
D.The query will perform a collection scan because the regular expression is not anchored at the beginning.
AnswerD

For an index on email to be used, the regular expression must be a prefix match (e.g., /^user/). The given regex /@example\.com$/ matches a suffix, so MongoDB cannot use the index to limit the scan. It will examine every document in the collection, which is inefficient for large datasets. This is the correct behavior.

Why this answer

MongoDB can use an index for regular expression queries only when the regex is anchored at the start of the string (e.g., /^prefix/). A regex that matches a suffix or an arbitrary substring cannot leverage the index's sorted order, so the query performs a full collection scan. The given query, which looks for emails ending with "@example.com", is not left-anchored and therefore cannot use the index efficiently.

Exam trap

The trap here is assuming that any regular expression can benefit from an index, but only left-anchored regexes can use an index effectively.

Ready to test yourself?

Try a timed practice session using only Indexing questions.