0
0
MongoDBquery~3 mins

Why When not to index in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if adding too many indexes actually makes your database slower?

The Scenario

Imagine you have a huge notebook where you write down everything you buy every day. Now, you want to find all the times you bought apples. Without any system, you have to flip through every page, which takes forever.

The Problem

Manually searching through all pages is slow and tiring. If you try to add a special tab for apples on every page, it might help, but if you add tabs for every single item, the notebook becomes bulky and hard to manage.

The Solution

Indexes in databases act like those tabs, helping you find data quickly. But adding too many tabs (indexes) can slow down writing new notes and make the notebook heavy. So, knowing when not to add an index keeps things balanced and efficient.

Before vs After
Before
db.collection.createIndex({ item: 1 })
db.collection.createIndex({ price: 1 })
db.collection.createIndex({ description: 1 }) // Index on every field
After
db.collection.createIndex({ item: 1 }) // Only index fields used in searches
What It Enables

Understanding when not to index helps keep your database fast and responsive, especially when adding or updating data.

Real Life Example

In a shopping app, you might index the 'product name' to find items quickly, but not index the 'description' field because it's rarely searched and would slow down updates.

Key Takeaways

Indexes speed up searches but slow down writes.

Not every field needs an index.

Choosing wisely keeps your database efficient.