Database
Top 100 MongoDB Indexes Interview Questions with Crisp Answers
A comprehensive collection of the top 100 MongoDB indexes interview questions with short, practical answers.
Basics of Indexes
-
What is an index in MongoDB?
A data structure that improves query performance by allowing fast lookups instead of full collection scans (COLLSCAN). -
What is the default index in MongoDB?
Every collection has a unique index on the_idfield that cannot be dropped. -
How do indexes improve performance?
They reduce the number of documents examined and disk I/O by storing sorted keys and pointers to documents. -
What is the cost of indexes?
Extra storage and write overhead — every insert/update/delete must update all relevant indexes. -
How do you create an index?
db.collection.createIndex({ field: 1 })(1 = ascending, -1 = descending). -
How do you list all indexes on a collection?
db.collection.getIndexes()ordb.collection.getIndexes().lengthfor the count. -
How do you drop an index?
db.collection.dropIndex("indexName")ordb.collection.dropIndex({ field: 1 }). -
Can you drop the
_idindex?
No. The_idindex is mandatory and cannot be dropped. -
What data structure does MongoDB use for indexes?
B-tree (implemented by WiredTiger). -
What is index selectivity?
The ratio of distinct values to total documents. High selectivity (more unique values) makes indexes more effective. -
What happens if no index exists for a query?
MongoDB performs a full collection scan (COLLSCAN). -
What is a covered query?
A query that can be satisfied entirely from the index without fetching full documents (IXSCAN + no FETCH stage). -
How do you check if a query uses an index?
Use.explain("executionStats")and look forIXSCAN(good) vsCOLLSCAN(bad). -
What does
totalDocsExaminedtell you?
Number of documents examined. Ideally close tonReturnedfor efficient queries. -
What is the working set?
The portion of data and indexes that must fit in RAM for optimal performance.
Index Types
-
What is a single-field index?
An index on one field. Direction (1 or -1) does not matter for single-field indexes because MongoDB can traverse in either direction. -
What is a compound index?
An index on multiple fields. Field order is critical. -
What is a multikey index?
An index automatically created when indexing an array field. One index entry is created per array element. -
What is a text index?
Supports full-text search on string content using$textoperator. One text index per collection. -
What is a geospatial index?
Supports location-based queries.2dspherefor spherical (Earth) data,2dfor planar data. -
What is a hashed index?
Indexes the hash of a field’s value. Useful for equality queries and shard key distribution. Does not support range queries. -
What is a wildcard index?
Indexes all fields or all fields matching a pattern ($**). Useful for flexible/schemaless documents. -
Can a compound index contain a hashed field?
No. Hashed indexes cannot be part of a compound index. -
How many fields can a compound index have?
Up to 32 fields. -
What is the maximum size of an index key?
1024 bytes. -
What is a unique index?
Enforces uniqueness on the indexed field(s). Duplicate values causeE11000duplicate key error. -
What is a sparse index?
Only indexes documents that contain the indexed field (skips missing/null fields). Legacy option; prefer partial indexes. -
What is a partial index?
Indexes only documents that match a filter expression (partialFilterExpression). More flexible than sparse. -
What is a TTL index?
Automatically expires documents after a specified time (expireAfterSeconds). Only works on date fields. -
What is a hidden index?
An index that is maintained but not used by the query planner. Useful for testing index removal safely. -
What is a collation index?
Supports language-specific string comparison rules (case-insensitive, accent-insensitive, etc.). -
Can you create an index on an embedded document field?
Yes, using dot notation:{ "address.city": 1 }. -
Can you index the entire embedded document?
Yes, but queries must match the exact document structure (order and fields). -
What is a case-insensitive index?
Created using a collation withstrength: 2(or similar). -
How many text indexes can a collection have?
Only one text index per collection. -
What operators does a text index support?
Primarily$textand$metafor text score. -
What is a 2dsphere index used for?
Geospatial queries on spherical Earth data (GeoJSON points, lines, polygons). -
What is a 2d index used for?
Legacy geospatial index for planar (flat) coordinate data. -
Can multikey indexes be compound?
Yes, but a compound multikey index can contain at most one array field. -
Do multikey indexes support covered queries?
Only if the query projects only the indexed fields and the array field is not projected as an array.
Compound Indexes & Query Patterns
-
What is the index prefix rule?
A compound index on{A:1, B:1, C:1}can be used for queries onA,A+B, orA+B+C. It cannot be used forBorCalone. -
What is the ESR rule?
Equality → Sort → Range. Optimal field order for compound indexes: equality fields first, then sort fields, then range fields. -
Why does field order matter in compound indexes?
MongoDB uses the index from left to right. After a range condition, remaining fields cannot be used efficiently for sorting. -
Can a compound index support sorting?
Yes, if the sort direction matches the index direction (or the reverse of the entire index). -
What happens if sort direction does not match the index?
MongoDB may perform an in-memory sort (SORT stage), which can be expensive or hit the 32 MB limit. -
Can you have multiple compound indexes that share prefixes?
Yes, but it is often redundant. Prefer one well-designed compound index. -
How do you index for a query with equality and range?
Put equality fields first, then the range field. -
How do you index for a query that filters and sorts?
Follow ESR: equality fields → sort field → range fields. -
What is index intersection?
MongoDB can use multiple indexes for a single query (usually less efficient than a single compound index). -
When is index intersection useful?
Rarely preferred. A well-designed compound index is almost always better. -
Can compound indexes be used for queries on trailing fields?
No. Only prefixes of the index can be used. -
What is the difference between
{a:1, b:1}and{b:1, a:1}?
They support different query patterns. The first supports queries starting witha; the second supports queries starting withb. -
How many compound indexes should you create?
As few as possible. Each index adds write overhead. Design for your most common query patterns. -
Can you use a compound index for a single-field query?
Yes, if the single field is the prefix of the compound index. -
What is the recommended way to name indexes?
Use explicit names:createIndex(..., { name: "status_date_idx" })for easier management.
Multikey, Text, Geospatial & Special Indexes
-
When is a multikey index created?
Automatically when you index a field that contains an array in any document. -
Can you create a multikey index on multiple array fields in one compound index?
No. A compound multikey index can include at most one array field. -
How do multikey indexes affect query performance?
They can increase index size significantly if arrays are large. -
What is the difference between indexing an array field and indexing array elements?
Indexing the array field creates a multikey index with one entry per element. -
Can text indexes be combined with other index types?
Limited. Text indexes have restrictions when combined with other fields. -
What language does a text index use by default?
English. You can specifydefault_languageor per-document language. -
How do you create a text index on multiple fields?
createIndex({ title: "text", content: "text" }). -
What is the text score?
A relevance score returned by$meta: "textScore"for ranking text search results. -
Can you create a geospatial index on a non-GeoJSON field?
Yes for2d(legacy), but2dsphererequires GeoJSON. -
What is the difference between
$nearand$geoWithin?
$nearreturns results sorted by distance;$geoWithinreturns documents within a shape (no sorting). -
What is a hashed index primarily used for?
Even distribution of data across shards when used as a shard key. Also supports equality queries. -
Does a hashed index support range queries?
No. -
What is a wildcard index useful for?
Collections with dynamic or unpredictable field names (schemaless data). -
How do you create a wildcard index on all fields?
createIndex({ "$**": 1 }). -
How do you create a wildcard index on specific fields?
createIndex({ "attr.$**": 1 }). -
Can wildcard indexes be sparse?
Yes, they can usesparse: trueor partial filter expressions. -
What is the difference between sparse and partial indexes?
Sparse skips missing fields. Partial indexes only documents matching a custom filter expression. -
When should you use a partial index?
When only a subset of documents needs to be indexed (e.g., only active users). -
Can a partial index be unique?
Yes. Uniqueness is enforced only on documents that match the partial filter. -
How often does the TTL monitor run?
Approximately every 60 seconds. Expiry is not exact.
Index Options & Constraints
-
What happens when you insert a duplicate into a unique index?
The operation fails with error code11000(duplicate key error). -
Can unique indexes contain null values?
Yes, but only one document can have a missing/null value for a sparse unique index. Non-sparse unique indexes treat null as a value. -
What is the difference between
sparse: trueandpartialFilterExpression?
Sparse is a special case of partial. Partial is more powerful and recommended. -
Can you create a TTL index on a non-date field?
No. TTL indexes require a date field (or an array of dates). -
Can you have multiple TTL indexes on a collection?
Yes, but each document can only be expired by one TTL index. -
What is a background index build?
Older versions built indexes in the background. Modern MongoDB builds indexes in a way that minimizes locking. -
What is the difference between foreground and background index builds?
Foreground builds lock the database. Background builds allow reads/writes but take longer. (Mostly historical in recent versions.) -
How do you create a unique sparse index?
createIndex({ email: 1 }, { unique: true, sparse: true }). -
What is collation strength?
Determines comparison sensitivity. Strength 1 = base characters only, Strength 2 = case-insensitive, Strength 3 = case-sensitive. -
Can you change an existing index’s options?
No. You must drop and recreate the index.
Query Optimization & Explain
-
What stages in explain() indicate a good index usage?
IXSCANfollowed by limitedFETCH(or no FETCH for covered queries). AvoidCOLLSCANand largeSORT. -
What is a blocking sort?
An in-memory sort that occurs when the index cannot provide the required order. Limited to 32 MB by default. -
How do you force a particular index?
Use.hint("indexName")or.hint({ field: 1 }). -
What does
executionStats.nReturnedmean?
Number of documents returned by the query. -
What does
executionStats.totalKeysExaminedmean?
Number of index keys examined. -
What is a covered query advantage?
No document fetch is needed, resulting in the fastest possible query performance. -
How can you make a query covered?
Project only fields that exist in the index (including_idif needed, or exclude_id). -
What is the impact of
$whereon indexes?
$wheregenerally cannot use indexes efficiently and forces a collection scan. -
Can regular expressions use indexes?
Only prefix (anchored) regexes can use indexes. Unanchored regexes (/abc/) cannot. -
What is the best way to monitor index usage?
Use$indexStatsaggregation stage ordb.collection.aggregate([{ $indexStats: {} }]).
Best Practices & Advanced Topics
-
What is the biggest risk of having too many indexes?
Write amplification — every write must update all indexes, increasing latency and storage. -
Should you index every field you query?
No. Index only fields used in high-frequency, selective queries. Prefer compound indexes. -
What is the recommended order for compound index fields?
Follow ESR: Equality fields first, Sort field next, Range fields last. -
How do you safely remove an index in production?
First hide the index (hideIndex), monitor performance, then drop it if safe. -
What should you check before creating a new index?
Query patterns (via profiler or logs), existing indexes, cardinality/selectivity, and write impact. Always validate withexplain().