Courseiva

CCNA Indexing And Performance Questions

30 questions · Indexing And Performance topic · All types, answers revealed

1
MCQmedium

What is the primary benefit of using a Covered Query in MongoDB?

A.It forces the data to stay in the WiredTiger cache.
B.It avoids reading the full document from disk.
C.It automatically compresses all returned data.
D.It eliminates the need for any index on the collection.
AnswerB

When an index contains all fields required by a query, MongoDB returns the data directly from the index. This removes the need to perform a costly disk fetch to retrieve the full document, significantly reducing I/O operations and improving the overall latency and throughput of the query.

Why this answer

A covered query is one where all the fields in the query projection exist within the index itself. Because the database can retrieve all necessary data directly from the index tree without needing to fetch the actual document from disk, it drastically reduces I/O. This is one of the most effective ways to optimize read performance for high-frequency queries in large collections.

Exam trap

Candidates often confuse covered queries with regular index scans, mistakenly believing that any query using an index avoids disk reads. However, fetching documents that are projected outside the index still requires reading from disk.

2
MCQmedium

Refer to the exhibit. What does this output indicate about the query performance?

A.The query is fully covered by an index.
B.The query requires an index to avoid a full collection scan.
C.The query is performing well because nReturned equals totalDocsExamined.
D.The index is being used, but it is not selective enough.
AnswerB

The presence of COLLSCAN signifies that no suitable index was found to narrow the search scope. To improve performance, an index should be created on the fields used in the query filter, which would allow the database to locate the necessary documents using an efficient index scan instead.

Why this answer

A 'COLLSCAN' indicates that the database is performing a full collection scan, reading every document to satisfy the query. The high number of docs examined relative to the returned documents suggests that the query is inefficient. In a production environment, this is a major performance bottleneck, as the database engine must load entire documents into memory to evaluate the filter, leading to high I/O and latency.

Exam trap

Candidates often confuse IXSCAN with COLLSCAN, mistakenly believing that a high number of examined documents in a full scan means the index is working effectively.

3
MCQeasy

A DBA notices that a query on the products collection uses an index scan but returns only a small fraction of documents. The index is { category: 1, price: 1 }. The query filters on category and price with a range condition on price. Which statement best describes why the index might still be efficient despite scanning many index entries?

A.The index scan is efficient because MongoDB automatically converts it to a collection scan when the selectivity is low.
B.The index scan is efficient because it can use the index bounds to limit the scan to the relevant category and price range, reducing the number of documents fetched.
C.The index scan is efficient because it avoids fetching documents entirely due to the index being covered.
D.The index scan is efficient because it uses the index only for sorting and not for filtering.
AnswerB

When a query filters on category (equality) and price (range), the index { category: 1, price: 1 } allows MongoDB to set index bounds for both fields. It can seek directly to the matching category and then scan only the price range within that category. This limits the number of index entries examined and the number of documents fetched, making the index scan efficient even if it examines many index keys, because it avoids a full collection scan.

Why this answer

The index { category: 1, price: 1 } supports efficient filtering when the query has an equality predicate on category and a range predicate on price. MongoDB can use index bounds to seek to the correct category and scan only the relevant price range, minimizing the number of documents fetched. This makes the index scan efficient despite examining many index entries.

Exam trap

The trap here is assuming that an index scan is inefficient simply because it examines many index keys, when the key benefit is avoiding a full collection scan and fetching only matching documents.

4
MCQhard

Refer to the exhibit. Which index is most effective for this query?

A.{ tags: 1 }
B.{ tags: 'hashed' }
C.{ tags: 1, _id: 1 }
D.No index is required for array fields.
AnswerA

A multikey index on the 'tags' array allows MongoDB to map each individual element of the array to the document. This enables efficient lookup for specific values like 'red' and 'blue', making it the optimal choice for queries using the $all operator on an array field.

Why this answer

The $all operator is used to find documents where the field contains all the specified elements. When indexing an array field, MongoDB creates a multikey index. A simple index on 'tags' is sufficient here because the multikey index structure inherently supports finding documents that contain specific array elements, enabling the query engine to efficiently narrow down the result set without scanning all documents in the collection.

Exam trap

Exams often tempt candidates to create complex multi-key or compound index variants for array queries when a basic single-field index already natively supports the operation.

5
MCQmedium

Which situation is best suited for a Multikey Index?

A.Indexing a collection where every document contains a simple numeric ID.
B.Querying documents based on specific elements inside an array field.
C.Improving the performance of large joins across multiple collections.
D.Enforcing unique constraints on non-array fields.
AnswerB

Multikey indexes are the standard solution for indexing array fields. They allow the database to map each individual array element to the corresponding document, making it possible to query the contents of arrays efficiently. Without a multikey index, querying an array field would result in a slow collection scan.

Why this answer

Multikey indexes are used when you need to index a field that contains an array. MongoDB creates an index entry for each element in the array, allowing you to efficiently query for documents containing specific array values. This is essential for applications managing tags, inventory lists, or user attributes stored as arrays, ensuring that queries filtering by these elements perform with high efficiency rather than scanning the entire collection.

Exam trap

Candidates mistakenly believe Multikey indexes are for general performance optimization, rather than specifically for indexing fields that contain arrays, leading to incorrect index selection for standard field queries.

6
MCQmedium

What is the consequence of having a high number of 'keysExamined' compared to 'nReturned' in a query?

A.The index is too small and needs to be rebuilt.
B.The query is inefficiently scanning the index.
C.The database is performing a cache miss.
D.The query will be automatically optimized.
AnswerB

When keysExamined is significantly higher than nReturned, the query engine is visiting many index entries that don't match the query. This indicates that the index is poorly suited for the query's filter, causing unnecessary index I/O and increasing the time it takes to return the results.

Why this answer

A large discrepancy between 'keysExamined' and 'nReturned' suggests that the index is not very selective or is being used inefficiently. The engine is scanning many index entries that do not match the query criteria, which is a major performance drain. Investigating the selectivity of the index and potentially adding more fields to the compound index can help narrow down the search and improve efficiency.

Exam trap

Candidates often assume that any index usage is efficient, failing to recognize that a high ratio of examined keys to returned documents indicates a poorly selective or unoptimized index.

7
MCQhard

When evaluating index performance, what is the impact of a 'partial index'?

A.It forces all documents in the collection to be indexed.
B.It allows for faster writes by indexing fewer documents.
C.It automatically makes all queries return faster.
D.It is only compatible with unique indexes.
AnswerB

Because a partial index only tracks a subset of documents, fewer index updates are required when documents are inserted or modified. This directly improves write throughput, especially in collections where the vast majority of documents do not match the criteria, effectively optimizing both index size and system performance.

Why this answer

Partial indexes allow you to index only a subset of documents that meet a specific filter condition. This reduces index size and the overhead of maintaining the index during writes, as only updates to documents matching the filter trigger an index update. This is highly effective for reducing memory usage when you only need to index documents with specific statuses, such as 'active' or 'pending', rather than the entire collection.

Exam trap

Test-takers frequently confuse partial indexes with sparse indexes, assuming partial indexes only omit null fields rather than applying arbitrary developer-defined filter expressions.

8
MCQmedium

A collection 'events' has a compound index { tenantId: 1, createdAt: -1 }. A developer runs db.events.find({ tenantId: "acme", createdAt: { $gte: ISODate("2024-01-01") } }).sort({ createdAt: -1 }).limit(50). The explain output shows the index is used but the query still performs a large in-memory sort. Which action resolves the sort performance issue?

A.Add a sort key to the index: { tenantId: 1, createdAt: -1, _id: 1 }.
B.Ensure the index is { tenantId: 1, createdAt: -1 } and verify the query does not use a collation or type mismatch that prevents index-provided sort.
C.Reverse the compound index to { createdAt: -1, tenantId: 1 }.
D.Create a separate single-field index on createdAt.
AnswerB

The compound index with equality field tenantId first and sort field createdAt second already satisfies the equality, sort, and range pattern, so the sort should be index-provided. A collation difference, a mismatched field type, or a $or/$in shape can silently force a blocking SORT stage, so confirming these conditions is the correct diagnostic step.

Why this answer

A compound index can provide both the equality match and the sort when the equality fields form the prefix and the sort field follows. With { tenantId: 1, createdAt: -1 }, the query's equality on tenantId and sort on createdAt should be served without an in-memory sort. A blocking SORT in explain therefore points to a mismatch such as collation, type, or query shape rather than a missing index.

Exam trap

The trap here is assuming any sort requires a new index, when a correctly ordered compound index already provides the sort and the real cause is a collation or type mismatch.

9
Multi-Selectmedium

A DBA is troubleshooting a slow query on a large collection. Which two techniques directly reduce the number of documents the query must examine for an equality-plus-range predicate? (Choose two.)

Select 2 answers
A.Create a compound index with the equality field first and the range field second.
B.Add a hint forcing the query to use the _id index.
C.Create a partial index with a filter expression matching the query's equality predicate.
D.Set the query's read concern to 'majority' to reduce examined documents.
E.Increase the index's fill factor using collMod to leave more space on pages.
AnswersA, C

Placing the equality field first gives the index a tight prefix bound, and the range field second allows the index to scan only the relevant range within that equality. This ordering lets the engine seek directly to matching keys rather than scanning broadly, directly cutting documents examined. It is a core index design rule for mixed equality and range predicates.

Why this answer

Reducing documents examined comes from narrowing the index scan. A compound index ordered equality-then-range lets the engine seek to the exact key range, and a partial index filtered on the equality predicate stores only relevant entries, shrinking the index. Both directly cut keys and documents examined.

Read concern, hint to _id, and page fill settings do not change the access path work for this predicate.

Exam trap

The trap here is treating consistency or storage-tuning knobs like read concern or fill factor as if they reduce the documents a query examines, when only index selectivity and bounds do.

10
MCQmedium

An e-commerce application frequently runs a query filtering by category and sorting by price descending. Which index structure provides the optimal performance for this access pattern?

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

The category field uses an ascending index prefix for equality matching, while the price field uses a descending direction that matches the requested sort order. This exact alignment allows the query engine to retrieve documents pre-sorted, completely bypassing expensive memory sorting operations.

Why this answer

To optimize queries with equality filters and descending sorts, the index must match the equality field first, followed by the sort field with the correct direction. Placing category first satisfies equality lookup, while setting price to negative one avoids in-memory sorting stages during execution.

Exam trap

Candidates often ignore the sort direction in index creation, assuming that {category: 1, price: 1} will optimize a query that sorts by price in descending order.

11
MCQhard

Refer to the exhibit. An application queries active user documents frequently, but explainPlan output reveals a COLLSCAN stage. What is the most appropriate remediation step?

A.Modify the application connection string to include readConcern level linearizable.
B.Create a single-field index on the status field using db.collection.createIndex({ status: 1 }).
C.Restart the primary database node to clear the query plan cache and force re-evaluation.
D.Increase the WiredTiger cache size configuration parameter to cache the entire collection in RAM.
AnswerB

Adding an index on the status field provides the query planner with a direct lookup path. Instead of performing an expensive collection scan, the query execution engine leverages an index scan to locate active documents instantaneously.

Why this answer

A COLLSCAN stage indicates that the query engine scanned every document in the collection because no suitable index was found. Creating an index on the filtered field enables the query planner to select an IXSCAN stage, drastically reducing disk reads and improving throughput.

Exam trap

Candidates often suggest multi-key indexes or complex compound indexes when a simple single-field index on the filtered field is the most direct and efficient solution to eliminate a COLLSCAN.

12
MCQhard

A DBA observes that a query with filter { a: 5, b: { $gt: 10 } } and sort { c: 1 } is using a collection scan despite the existence of an index { a: 1, b: 1, c: 1 }. The DBA wants to improve performance. Which action is most likely to allow the index to support both the filter and the sort?

A.Create a new index { a: 1, c: 1, b: 1 } so that the sort field c comes before the range field b.
B.Create a partial index on { a: 1, b: 1, c: 1 } with a filter on b > 10, which will allow the sort to use the index.
C.Add a separate index on { c: 1 } and rely on the query planner to perform an index intersection with the existing index.
D.Modify the query to remove the range condition on b, so the existing index can support the sort on c.
AnswerA

The current index { a: 1, b: 1, c: 1 } cannot support the sort on c because b is a range predicate, which breaks the index prefix for sorting. After the equality on a, the next key is b, but b is not an equality; it is a range. The index can use a and b for filtering, but the sort on c cannot be satisfied because the index order after b is c, but b varies. By reordering the index to { a: 1, c: 1, b: 1 }, the equality on a is followed by the sort key c, allowing the index to provide sorted results. The range on b can then be applied as an index filter on the remaining key. This is the correct approach.

Why this answer

The index { a: 1, b: 1, c: 1 } cannot support the sort on c because b is a range predicate, which means the index order after the equality on a is determined by b, not c. To support both the filter and the sort, the index should be reordered so that the sort field c follows the equality field a, and the range field b comes last. The index { a: 1, c: 1, b: 1 } allows the equality on a to bound the prefix, then the sort on c to be satisfied by the index order, and finally the range on b to be applied as an index filter.

Exam trap

The trap here is assuming that a compound index can support a sort on a field that comes after a range predicate in the index key pattern.

13
MCQmedium

When would you choose to create a Partial Index instead of a standard index?

A.When you need to ensure the index covers all documents.
B.When only a subset of data is frequently queried.
C.To improve performance for all possible queries.
D.To automatically shard the collection data.
AnswerB

Partial indexes reduce index size by only including documents that meet a filter condition. This is highly effective when your application only queries active or specific subsets of data, leading to smaller index memory footprints and faster performance for those specific, high-frequency query patterns compared to full indexes.

Why this answer

Partial indexes are designed to index only a subset of documents that meet a specific filter expression. They are highly efficient when queries only target a small, specific portion of a large collection. By reducing the size of the index in memory and on disk, partial indexes lower storage costs and decrease the impact on write operations while maintaining query performance for the intended subset of data.

Exam trap

Candidates often choose sparse indexes instead of partial indexes, confusing sparse indexing behavior with the ability to define custom, complex filter expressions for subsets of data.

14
Multi-Selecthard

Which TWO of the following scenarios are best handled by a Hashed Index?

Select 2 answers
A.Range-based queries on numeric fields.
B.Sharding a collection on a high-cardinality key.
C.Equality lookups on unique values.
D.Sorting results by the indexed field.
E.Text search on long strings.
AnswersB, C

Hashed indexes are the industry standard for sharding keys to ensure an even distribution of data across shards. By hashing the shard key, you prevent the 'hot shard' problem, ensuring that writes are spread out across all nodes in the cluster, which is vital for scalability.

Why this answer

Hashed indexes map the hash of the field value to the document, which is excellent for distributing data evenly across shards. They are ideal for fields with high cardinality that are primarily used for equality lookups. They do not support range-based queries, so they should not be used for fields where inequality filtering (like greater than or less than) is the primary query pattern.

Exam trap

Candidates incorrectly assume hashed indexes support range queries like greater than or less than, leading to poor query optimization and missing results.

15
MCQeasy

A DBA needs a query that returns only the fields name and email from a 'users' collection, filtered by an equality on email, to avoid fetching full documents from disk. Which index design supports this efficiently?

A.A single-field index on email, relying on the query's projection to fetch name from the document.
B.A text index on name and email to cover both fields.
C.A compound index { email: 1, name: 1 } so the query can be covered by the index.
D.A hashed index on email to speed equality matching.
AnswerC

When the index contains every field referenced by the query's filter and projection, MongoDB can return results directly from the index without fetching documents. An index { email: 1, name: 1 } supports the equality on email and supplies name, so the projection is satisfied entirely from index keys, eliminating document fetches and reducing examined documents to index keys only.

Why this answer

A covered query is one whose filter and projection are both satisfied by the index, so no document fetch is needed. Including every projected field in the index, as with { email: 1, name: 1 }, lets the engine return results straight from index keys. Single-field, hashed, and text indexes cannot supply the projected name field, so they cannot cover this query.

Exam trap

The trap here is assuming any index on the filter field avoids document fetches, when coverage requires the index to also contain every projected field.

16
MCQmedium

An operations engineer notices that a frequently executed aggregation pipeline fails with a 'Exceeded memory limit for $sort' error. Which index configuration best resolves this memory constraint?

A.Create a wildcard index across all collection fields to capture unpredictable aggregation pipeline projections.
B.Create a compound index matching the query's match filter fields followed by the sort fields in exact order.
C.Increase the global cluster parameter maxInMemorySortBytes beyond the default allocation limit.
D.Enable allowDiskUse on every query connection string globally across the application configuration.
AnswerB

Matching the equality and sort fields within a single compound index enables the storage engine to deliver documents in the precise sorted order required by the pipeline. This eliminates the need for an in-memory sort stage, safely avoiding the strict RAM threshold limits.

Why this answer

MongoDB restricts in-memory operations like sorting to a fixed buffer size. When a query cannot satisfy its sort requirements from an index, it loads documents into memory. Providing a compound index containing the query's equality, range, and sort fields allows the execution engine to stream sorted results directly.

Exam trap

Candidates often create an index only on the sort field, forgetting that the query filter must also be satisfied by the index to avoid an in-memory sort operation.

17
Multi-Selectmedium

A DBA is designing indexes for a collection that stores user activity logs. The collection has fields: user_id, action, timestamp, and metadata (an embedded document). The most common queries are: (1) find all actions for a given user_id sorted by timestamp descending; (2) find all users who performed a specific action within a time range. Which TWO indexes would best support these queries? (Choose two.)

Select 2 answers
A.{ metadata: 1 }
B.{ user_id: 1, timestamp: -1 }
C.{ user_id: 1, action: 1, timestamp: -1 }
D.{ timestamp: 1 }
E.{ action: 1, timestamp: 1 }
AnswersB, E

This index supports query (1) by providing an equality match on user_id and a sort on timestamp descending. The index prefix is user_id, and the sort field follows, so the index can be used efficiently for both filtering and sorting, avoiding an in-memory sort.

Why this answer

The two indexes that best support the queries are { user_id: 1, timestamp: -1 } for query (1) and { action: 1, timestamp: 1 } for query (2). The first provides an equality match on user_id and a sort on timestamp, while the second provides an equality match on action and a range on timestamp. These indexes align with the equality-sort and equality-range patterns, ensuring efficient index usage.

Exam trap

The trap here is creating a single compound index that attempts to cover both queries but fails to support the sort in query (1) because of an extra field in between.

18
MCQmedium

When evaluating the performance of a 'hint' in MongoDB, what should you keep in mind?

A.Hints are always faster than the optimizer's choice.
B.Hints should be used for all production queries.
C.Hints prevent the optimizer from adapting.
D.Hints are only available for aggregation queries.
AnswerC

A hint overrides the query optimizer, forcing it to use a specific index regardless of cost. This prevents the system from choosing better plans as the data distribution changes. This can result in performance regression as the application scales and the original index choice is no longer optimal.

Why this answer

Using a hint forces the optimizer to use a specific index, ignoring its own cost-based selection. While this can sometimes be useful for troubleshooting or very specific cases where the optimizer makes a poor choice, it is generally discouraged because it prevents the database from adapting to data changes. As the data distribution evolves, a hinted index might become suboptimal, leading to degraded performance compared to a dynamic plan.

Exam trap

Test-takers frequently think hints permanently improve performance by hardcoding the best execution path, ignoring the fact that database workloads and data distributions change over time.

19
MCQhard

A collection 'logs' receives continuous inserts and is queried by both timestamp ranges and a rarely used severity field. A DBA creates six indexes to cover every query variant, and now insert throughput has dropped sharply while index sizes dominate the working set. Which action best restores insert throughput while preserving the important query paths?

A.Convert all indexes to hashed indexes to reduce index size.
B.Set the collection's write concern to w:0 to avoid index maintenance waits.
C.Increase the WiredTiger cache size so more indexes stay resident.
D.Drop redundant indexes and consolidate overlapping ones into compound indexes that serve multiple query shapes.
AnswerD

Each additional index must be maintained on every insert, so excess and overlapping indexes multiply write cost and consume cache. Reviewing index usage, removing unused or redundant ones, and merging overlapping prefixes into compound indexes reduces per-insert maintenance while still serving the timestamp range and severity queries. This directly restores insert throughput without sacrificing needed access paths.

Why this answer

Every index adds maintenance work to each insert, update, and delete, so a collection with many overlapping indexes suffers write amplification and cache pressure. Auditing index usage, dropping unused or redundant indexes, and consolidating overlapping prefixes into compound indexes reduces per-write maintenance while keeping the timestamp range and severity access paths covered. Write concern and cache tuning do not remove index maintenance cost.

Exam trap

The trap here is reaching for write concern or cache tuning to fix insert slowdown, when the actual cost is index maintenance from too many overlapping indexes.

20
MCQeasy

A support team reports that a MongoDB 6.0 replica set is experiencing slow queries on a collection where almost every document has a unique value for the field status. A developer suggests creating a hashed index on status to speed up equality lookups. Which outcome should the DBA expect?

A.Hashed indexes provide no benefit for equality queries on high-cardinality fields and should not be used.
B.A hashed index will improve equality query performance but will prevent the use of range queries on status.
C.A hashed index will not improve equality query performance and is primarily intended for even data distribution in sharded clusters.
D.Hashed indexes are ideal for equality lookups and will outperform a standard B-tree index for this query pattern.
AnswerC

Hashed indexes are designed to distribute documents evenly across shards by hashing the shard key value. For a single-node equality lookup, a standard B-tree index is usually sufficient and more versatile because it supports range queries and sorted access. Since the field already has high cardinality, a B-tree index on status would provide efficient equality lookups without the drawbacks of hashed indexes, which cannot be used for range queries.

Why this answer

Hashed indexes are optimized for even distribution of values, which is critical for sharding but not for improving equality query performance on a single replica set. A standard B-tree index on a high-cardinality field like status already provides efficient equality lookups and supports range queries. Therefore, a hashed index would not be the right choice to speed up these queries; it is better suited for shard keys that need uniform distribution.

Exam trap

The trap here is confusing the purpose of hashed indexes, which is even data distribution for sharding, with general query performance optimization.

21
MCQhard

Refer to the exhibit. The explain output shows a SORT stage wrapping an IXSCAN stage. What is the performance implication of this execution plan?

A.The query is fully optimized because it leverages an index scan for filtering records.
B.The query engine performed an in-memory sort because the index did not support the requested sort order.
C.The query executed a full collection scan across all cluster nodes.
D.The storage engine automatically converted the query into a covered query.
AnswerB

The status index only supports filtering on status. Because the query also requested a sort on created, the database had to sort the resulting documents in memory, which can exceed memory limits and degrade overall execution speed.

Why this answer

When a SORT stage wraps an IXSCAN stage, it means the index used for filtering did not satisfy the sort requirement. The query engine had to load the matching documents into memory to sort them, risking memory limit exceptions on large result sets.

Exam trap

Students often assume that any index usage guarantees optimal performance, overlooking how a SORT stage wrapping an IXSCAN reveals that the index failed to cover the requested sort order.

22
MCQmedium

An application frequently queries a large collection using two fields: 'category' (equality) and 'timestamp' (range). Which index strategy provides the most efficient execution plan?

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

Following the ESR rule, this index allows MongoDB to perform an index seek on the equality field and then efficiently traverse the range of timestamps. This significantly reduces the number of index nodes visited and documents loaded into memory, resulting in optimal query performance and resource utilization.

Why this answer

The ESR (Equality, Sort, Range) rule dictates that equality fields should come first in a compound index, followed by sort fields, and finally range fields. By placing 'category' first, MongoDB eliminates most irrelevant documents immediately. The 'timestamp' field follows, allowing the engine to leverage the index for range filtering.

This minimizes memory usage and prevents costly full collection scans, which is critical for maintaining performance as data volume scales.

Exam trap

Candidates often put the range field before the equality field, violating the ESR rule. This leads to inefficient index usage and slower query performance on large datasets.

23
MCQhard

A sharded cluster experiences poor query performance because a targeted query targeting a specific shard key still results in a scatter-gather operation across all shards. What is the root cause?

A.The chunk migration threshold was set too low, causing frequent balancing cycles across shards.
B.The query predicate completely omitted the shard key or its valid prefix fields.
C.The collection was created as unhashed, preventing the mongos router from hashing query inputs.
D.The balancer process was paused, leaving uneven document distribution across cluster shards.
AnswerB

Without the shard key or a valid prefix in the query filter, the mongos query router cannot determine which shard holds the matching data. Consequently, it must broadcast the query to all shards in the cluster, creating an inefficient scatter-gather operation.

Why this answer

To target a specific shard directly, a query must include the exact shard key or a valid prefix of the shard key in its filter predicate. Omitting the shard key forces the mongos router to query every shard in the cluster to assemble the final result set.

Exam trap

Candidates confuse 'querying by the shard key' with 'including the shard key in the query predicate.' Even if you know the shard key, the query must explicitly filter by it.

24
MCQmedium

Why should you avoid creating too many indexes on a single collection?

A.It prevents the use of sharding.
B.It increases the cost of write operations.
C.It automatically disables the WiredTiger cache.
D.It forces queries to use a collection scan.
AnswerB

Each index must be updated whenever a document is inserted, modified, or deleted. Maintaining these B-trees adds synchronous I/O overhead to every write, which can create significant latency and limit the write throughput of the application as the number of indexes grows on the collection.

Why this answer

Every index adds overhead to every write operation (insert, update, delete) because the database must maintain the index structure alongside the collection. Furthermore, indexes consume significant memory, and if the working set (the data and indexes most frequently accessed) exceeds available RAM, the database will experience frequent page faults from disk, leading to severe performance degradation across all types of operations.

Exam trap

Many students mistakenly believe that more indexes only impact disk space, forgetting the significant performance penalty excessive indexes impose on writes and memory usage.

25
MCQhard

A DBA is reviewing a query that performs a sort on a field named score in descending order. The collection has an index { score: 1 }. The query also includes a filter on a field named active with an equality condition. The DBA observes that the query planner chooses a collection scan and performs an in-memory sort. Which index would allow the query to use an index for both the filter and the sort?

A.{ score: -1, active: 1 }
B.{ score: 1, active: 1 }
C.{ active: 1, score: 1 }
D.{ active: 1, score: -1 }
AnswerD

The query has an equality filter on active and sorts by score descending. An index with active first (equality) and score second in descending order allows MongoDB to filter on active and then scan the index in score descending order. This satisfies both the filter and the sort without an in-memory sort. The leading equality field ensures the index can be used efficiently for the filter, and the sort field follows in the correct direction.

Why this answer

The query filters on active with equality and sorts by score descending. The optimal index places the equality field first and the sort field second in the matching direction: { active: 1, score: -1 }. This allows MongoDB to use the index for the filter and to provide the descending sort order directly, avoiding an in-memory sort and improving performance.

Exam trap

The trap here is assuming that an index on the sort field alone is sufficient, when the equality filter field should precede the sort field for efficient compound index usage.

26
MCQeasy

Which property of a field makes it a poor candidate for an index?

A.The field is frequently used in filter criteria.
B.The field contains unique identifiers like UUIDs.
C.The field has very low cardinality.
D.The field is a numeric timestamp.
AnswerC

Low cardinality means the field has very few unique values across a large number of documents. When you search for one of these values, the index may return a huge portion of the collection, making a full collection scan more performant than using the index itself.

Why this answer

Low cardinality fields, such as those with only two or three unique values, provide little benefit when indexed. MongoDB's query optimizer often skips these indexes because a collection scan is usually faster than traversing the B-tree for a large percentage of the dataset. Identifying high-cardinality fields is essential for building effective indexes that genuinely speed up data retrieval rather than just adding overhead to write operations.

Exam trap

Candidates frequently assume indexing every field is universally beneficial, failing to recognize that low-cardinality fields degrade performance and waste resources.

27
MCQhard

Refer to the exhibit. A developer attempts to run a query using both 'tags' and 'location' in a single $and operation. What is the expected behavior regarding index usage?

A.It will always use both indexes simultaneously.
B.It will fail because compound indexes are required.
C.The optimizer may choose an index intersection plan.
D.It will ignore all indexes and scan the collection.
AnswerC

MongoDB's query optimizer can use index intersection to combine multiple single-field indexes to satisfy a query. It will evaluate the candidate indexes and, if the cost analysis indicates that intersection is the most efficient path, it will create a plan using both indexes for the filter.

Why this answer

MongoDB can utilize multiple indexes for a single query through an 'index intersection' execution plan. However, the query optimizer decides whether to perform an intersection or use just one index based on cost. For complex queries involving geo-spatial data and arrays, intersection might be less efficient than a single compound index, and the optimizer may choose a collection scan if intersection costs are deemed too high.

Exam trap

Candidates often assume that MongoDB will always use an index intersection for any query with multiple conditions, ignoring the fact that the optimizer prioritizes single compound indexes over intersection plans.

28
MCQmedium

A DBA needs to optimize a query that filters on a field with high cardinality, such as email, and also sorts on a low cardinality field, such as country. The query is { email: "user@example.com" } with sort { country: 1 }. Which index would best support this query?

A.{ email: 1 }
B.{ country: 1 }
C.{ country: 1, email: 1 }
D.{ email: 1, country: 1 }
AnswerD

This index supports the query by first filtering on email (equality) and then providing sorted results by country. The index prefix is email, and the sort field country follows. Since email is highly selective, the index will quickly locate the matching document(s) and the sort on country is satisfied by the index order for that email.

Why this answer

The compound index { email: 1, country: 1 } is optimal because it allows an equality match on email, which is highly selective, and then provides sorted results by country. The index order matches the query pattern: equality first, then sort. This avoids an in-memory sort and minimizes the number of documents examined.

Exam trap

The trap here is thinking that the sort field should be first in the index, but with an equality filter on a high-cardinality field, the equality field should lead.

29
MCQmedium

An application frequently queries a large collection by 'user_id' and 'status', sorting the results by 'timestamp'. Which index provides the most efficient execution plan?

A.{ timestamp: 1, user_id: 1, status: 1 }
B.{ user_id: 1, timestamp: 1, status: 1 }
C.{ user_id: 1, status: 1, timestamp: 1 }
D.{ user_id: 1, status: 1 }
AnswerC

This structure follows the ESR rule perfectly. The equality fields appear first, narrowing down the search space, followed by the field required for sorting. This combination allows the query engine to retrieve documents in the desired order without performing an additional, resource-intensive sort operation after fetching the data.

Why this answer

To optimize this query, the ESR (Equality, Sort, Range) rule must be applied. The 'user_id' and 'status' fields are equality filters, while 'timestamp' is used for sorting. An index of {user_id: 1, status: 1, timestamp: 1} allows MongoDB to satisfy the query filters and provide the sort order directly from the index, avoiding a blocking sort operation in memory which is critical for performance on large collections.

Exam trap

Candidates frequently ignore the ESR rule, creating indexes that include fields in the wrong order, which prevents the query engine from efficiently using the index for both filtering and sorting.

30
MCQmedium

A MongoDB DBA observes that a query with filter { status: "active", created_at: { $gte: ISODate("2024-01-01") } } and sort { created_at: -1 } is performing a collection scan. The collection has an index { status: 1, created_at: -1 }. Which of the following best explains why the index is not being used efficiently?

A.The index prefix is not equality on the leading field, so the sort cannot be satisfied by the index.
B.The index { status: 1, created_at: -1 } should support both the filter and sort; the collection scan indicates a different issue such as index not being built or query planner choosing a different plan.
C.The index is a partial index that excludes documents with status "active", so it cannot be used.
D.The index does not include the sort field as the first field, so the sort cannot use the index.
AnswerB

With equality on status and a range on created_at, the index can efficiently filter and provide sorted results because the index prefix is equality and the sort field follows. A collection scan suggests the index may be missing, invalid, or the planner selected a less efficient plan due to statistics.

Why this answer

The compound index { status: 1, created_at: -1 } is designed to support queries that filter on status with equality and sort on created_at. The index prefix (status) is an equality match, allowing the index to be used for both filtering and sorting. A collection scan indicates that the index might not exist, be invalid, or the query planner chose a different plan due to factors like low selectivity or stale statistics.

Exam trap

The trap here is assuming that the index cannot support the sort because the sort field is not the first field, ignoring the equality condition on the leading field.

Ready to test yourself?

Try a timed practice session using only Indexing And Performance questions.