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

Popular posts from this blog

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🧡 Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

πŸš€ “How are Virtual Threads different from Thread Pools?” 😡 “Are they OS threads or JVM threads?” πŸ™ƒ “Should I still use CompletableFuture?” 🀯 “How do I even use them in real-time microservices?” 🧠 What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. 🧠 What is the OS Kernel? πŸ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory 🧠 Schedules threads πŸ•’ Talks to hardware πŸ’» Handles I/O operations πŸ“¨ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. πŸ–Ό️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...