MongoDB — Indexing Fundamentals
Understand B-tree indexes, single field indexes, and how indexes transform slow COLLSCAN scans into fast IXSCAN lookups.
1What is an Index & Why Do You Need It?
Without an index, MongoDB must scan every single document in a collection (called a COLLSCAN). An index is a specialized B-tree data structure that stores a sorted list of field values, allowing MongoDB to perform fast logarithmic lookups (called an IXSCAN).
Creating an Index
// Create ascending index on email field
db.users.createIndex({ email: 1 });
// List all indexes on collection
db.users.getIndexes();
// Drop an index
db.users.dropIndex("email_1");
2The Cost of Indexing
⚠️ Index Trade-offs:
- Faster Reads: Reduces query execution time from seconds to milliseconds.
- Slower Writes: Every
insertOne()ordeleteOne()must update both the document AND all associated indexes. - RAM Memory Usage: Indexes must fit entirely inside WiredTiger RAM cache for optimal speed.