Problem Statement
How do indexes improve query performance in MongoDB and what are the trade-offs?
Explanation
Indexes improve query performance by creating a sorted data structure that allows MongoDB to quickly locate documents without scanning the entire collection. Instead of examining every document, MongoDB can use a B-tree index to jump directly to matching documents.
For example, without an index on the age field, finding users with age 30 requires scanning all documents, which is slow for large collections. With an index, MongoDB can find the relevant documents in logarithmic time.
The trade-offs are that indexes consume disk space and memory. Each index requires storage for the index data structure. Additionally, indexes slow down write operations because MongoDB must update all relevant indexes whenever you insert, update, or delete documents. Therefore, you should create indexes strategically based on your most common query patterns, not on every field.
Code Solution
SolutionRead Only
// Without index - scans all documents
db.users.find({ email: "alice@example.com" })
// docsExamined: 100000, executionTimeMillis: 150
// Create index
db.users.createIndex({ email: 1 })
// With index - fast lookup
db.users.find({ email: "alice@example.com" })
// docsExamined: 1, executionTimeMillis: 2