🍃 What is MongoDB?
MongoDB is a NoSQL document-based database that stores data in JSON-like format. Instead of rows and columns, it uses collections and documents. This makes it super flexible and schema-less — perfect for fast-moving modern apps 🚀.
SQL = Tables, Rows, Columns 📊
MongoDB = Collections, Documents 📚
❓Why Indexes Matter
Imagine searching a phonebook without alphabetical order — painful, right? 😅 Indexes make your searches faster by letting MongoDB skip scanning every document.
🧠 Types of Indexes in MongoDB
1️⃣ Single Field Index
Most basic and common. You index one field.
db.users.createIndex({ "name": 1 })
1 = ascending, -1 = descending. Used for queries like { name: "Priya" }.
2️⃣ Compound Index
Multiple fields combined to improve multi-field queries.
db.orders.createIndex({ "customerId": 1, "orderDate": -1 })
Order of fields matters! MongoDB can use prefix fields efficiently.
3️⃣ Text Index
Used for searching text phrases in string fields — supports partial matches and relevance scoring.
db.blogs.createIndex({ "content": "text", "title": "text" })
Then query like:
db.blogs.find({ $text: { $search: "MongoDB index" } })
4️⃣ Multikey Index
When field is an array — MongoDB indexes each array element.
db.products.createIndex({ "tags": 1 })
Query example: db.products.find({ tags: "database" })
5️⃣ Hashed Index
Distributes values evenly for sharding or hashed lookups.
db.users.createIndex({ "email": "hashed" })
6️⃣ TTL (Time-To-Live) Index
Auto-deletes documents after a given time — perfect for logs, sessions ⏳.
db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
7️⃣ Geospatial Index
Used for location-based queries 📍.
db.places.createIndex({ location: "2dsphere" })
8️⃣ Wildcard Index
For dynamic fields when you don’t know which ones to index.
db.dynamic.createIndex({ "$**": 1 })
9️⃣ Unique Index
Ensures values are not duplicated.
db.users.createIndex({ "email": 1 }, { unique: true })
🔟 Partial / Sparse Index
Indexes only documents meeting a condition (saves space!).
db.users.createIndex({ age: 1 }, { partialFilterExpression: { age: { $gte: 18 } } })
📊 Quick Comparison Table
| Index Type | Use Case | Example |
|---|---|---|
| Single | One field | { name: 1 } |
| Compound | Multi-field queries | { age:1, city:1 } |
| Text | Text search | { title:"text" } |
| Hashed | Sharding / random lookup | { id:"hashed" } |
| TTL | Auto delete | { createdAt:1 } |
🎯 Real Example — Speed Boost!
Query before index:
db.users.find({ name: "Priya" })
Took 2.3 sec ⏳
After index:
db.users.createIndex({ name: 1 })
Took 0.02 sec ⚡
🗣️ Interview Quickfire Q&A
- 💬 Q: What’s the default index in MongoDB?
A: The_idfield — automatically indexed! - 💬 Q: How is text index different from search index?
A: Text index = keyword search. Search index (Atlas Search) = full Lucene-based search engine with scoring. - 💬 Q: Can we have multiple text indexes per collection?
A: Nope ❌ Only one text index allowed per collection.
🏁 Conclusion
Indexes are the superpower of MongoDB ⚙️ — they turn slow lookups into lightning-fast queries ⚡. But use wisely: too many indexes = slower writes.
db.collection.explain("executionStats") to see if an index is actually used.
🚀 Keep learning, keep indexing smart! 🍃
Comments
Post a Comment