Mongodb Guide

When NOT to Use Indexing in MongoDB

1. Definition

Although indexing improves read performance, it is not always beneficial. In some cases, indexes can slow down operations and consume extra resources.

2. When NOT to Use Indexing

  • When the collection has very small data
  • When fields are rarely used in queries
  • When write operations (insert/update/delete) are frequent
  • When data changes very often
  • When queries return most of the documents

3. Why Not to Use Indexing

  • Indexes consume extra memory/storage
  • Slows down write operations
  • Maintenance overhead for updating indexes
  • Unnecessary indexes reduce performance

4. How It Affects Performance

  • Each insert/update must update indexes
  • More indexes = more work for database
  • Can increase storage usage significantly
  • May slow down overall system

Example

// Not useful index (rarely used field)
db.users.createIndex({ randomField: 1 });

// Query returns most documents (index not helpful)
db.users.find({ age: { $gt: 0 } });

5. Best Practice

  • Create indexes only on frequently queried fields
  • Avoid unnecessary indexes
  • Monitor performance before adding indexes
  • Balance between read and write performance

Index vs No Index (When Not Needed)

ScenarioUse Index?
Small dataset❌ No
Frequent writes❌ No
Frequent search✅ Yes
Sorting/filtering large data✅ Yes

Interview Points

  • Indexes improve read but slow down writes
  • Not useful for small datasets
  • Avoid indexing rarely used fields
  • Always balance read vs write performance