Skip to main content

🔥 MongoDB Index Types Explained — With Real Examples, Colors & Interview Tips

🍃 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 🚀.

💡 Difference vs SQL Databases:
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.

⚡ Tip: Without indexes, MongoDB performs a collection scan — meaning it checks every record. That’s fine for 10 docs... not for 10 million!

🧠 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 TypeUse CaseExample
SingleOne field{ name: 1 }
CompoundMulti-field queries{ age:1, city:1 }
TextText search{ title:"text" }
HashedSharding / random lookup{ id:"hashed" }
TTLAuto 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 _id field — 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.

💚 Pro Tip: Always check your queries with db.collection.explain("executionStats") to see if an index is actually used.

🚀 Keep learning, keep indexing smart! 🍃

Comments