Why Indexing Improves Performance in MongoDB
1. Definition
Indexing improves performance in MongoDB by reducing the amount of data the database needs to scan when executing a query, allowing faster data retrieval.
2. Simple Understanding
👉 Without index: MongoDB scans every document (slow)
👉 With index: MongoDB directly jumps to the required data (fast)
3. When It Matters
- Large datasets
- Frequent search queries
- Filtering and sorting operations
- High-performance applications
4. Where It Helps
- find() queries
- Sorting data
- Filtering records
- Backend APIs
5. Why It Improves Performance
- Avoids full collection scan
- Reduces number of documents checked
- Uses efficient data structure (like B-Tree)
- Faster lookup of matching records
6. How It Works Internally
- Creates a sorted structure of indexed fields
- Stores field values with document references
- Searches index instead of full collection
- Returns matching documents quickly
Example
// Without index (slow)
db.users.find({ name: "Manaswini" });
// Create index
db.users.createIndex({ name: 1 });
// With index (fast)
db.users.find({ name: "Manaswini" });Without vs With Index
| Operation | Without Index | With Index |
|---|---|---|
| Search | Full scan | Direct lookup |
| Speed | Slow | Fast |
| Efficiency | Low | High |
7. Trade-Off
- Faster reads
- Slower writes (insert/update)
- Extra storage required
Interview Points
- Index avoids full collection scan
- Uses efficient data structure (B-Tree)
- Improves query speed significantly
- Trade-off: read vs write performance