Explain indexing in MongoDB.
Instruction: Describe what indexes are, why they are important in MongoDB, and give examples of different types of indexes.
Updated
Official answer
Indexes provide alternative access paths so a query may examine fewer records or avoid an explicit sort. MongoDB supports single-field and compound indexes, multikey indexes for arrays, and specialized types such as geospatial, text and hashed indexes. Select an index from actual filter, sort and projection patterns.
For a compound index, field order and the query's predicates matter. Equality, sort and range considerations are useful design guidance, but verify the resulting plan and measured workload. An index on one field does not make every query involving that field efficient.
Hashed indexes transform indexed values. They can support equality lookups and hashed sharding, but generally do not support range access in original value order. Hashing a low-cardinality or very frequent value does not remove that skew, and hashing does not guarantee uniform load. Hashed indexes also have restrictions, including no multikey arrays and no unique constraint on the hashed index itself.
Indexes consume storage/cache and add work to inserts/deletes and updates that affect indexed values. Inspect executionStats, examined keys/documents, latency and write overhead before and after a change. Keep necessary uniqueness and access-path indexes, and remove redundant indexes only after reviewing actual usage and operational requirements.
Related Questions
-
easy
-
medium
-
medium
-
hard
-
hard
-
hard