MongoDB Indexing & Search
MongoDB Indexing & Search 🔍⚡
Without indexes, MongoDB performs a collection scan, which is slow for big data.
What is Indexing in MongoDB?
-
Index = special data structure
-
Improves query performance
-
Similar to index in a book
-
Stored separately from documents
📌 Trade-off: Faster reads, slightly slower writes
1️⃣ Create an Index
Syntax
Example: Index on name
Output:
2️⃣ Types of Indexes in MongoDB
🔹 Single Field Index
🔹 Compound Index (Multiple Fields)
📌 Order matters in compound indexes.
🔹 Unique Index
❌ Prevents duplicate values.
🔹 Text Index (Search)
Used for full-text search.
🔹 Hashed Index
Used in sharding.
3️⃣ View Indexes
4️⃣ Drop an Index
Or drop all:
5️⃣ Search Using Indexes
Normal Search
Uses index if available.
Range Search
6️⃣ Text Search (Full-Text Search)
Create Text Index (Once)
Search Text
Sort by Relevance
7️⃣ Explain Query (Check Index Usage) 🔎
Look for:
-
✅
IXSCAN→ index used -
❌
COLLSCAN→ full collection scan
8️⃣ Indexing with Aggregation
📌 Index on course improves $match performance.
SQL vs MongoDB Indexing
| SQL | MongoDB |
|---|---|
| CREATE INDEX | createIndex() |
| FULL TEXT SEARCH | Text Index |
| EXPLAIN PLAN | explain() |
Best Practices 👍
-
Index frequently queried fields
-
Use compound indexes wisely
-
Avoid too many indexes
-
Always check with
explain() -
Place
$matchearly in aggregation
Common Mistakes ❌
-
Creating unnecessary indexes
-
Wrong field order in compound index
-
Expecting text index to behave like Google search
