Indexing & Performance

Node js 10 min min read Updated: Mar 30, 2026 Intermediate
Indexing & Performance
Intermediate Topic 5 of 10

Indexing & Performance in MongoDB

As the amount of data in a database grows, query performance becomes more important. If MongoDB has to scan every document in a collection to find matching records, the application can become slow and inefficient. This is where indexing plays a major role.

Indexes help MongoDB locate data faster, just like an index in a book helps you find a topic quickly without reading every page. Proper indexing improves query speed, reduces response time, and helps applications perform better at scale.

Key Concept: Indexes improve query performance by helping MongoDB find matching documents faster instead of scanning the entire collection.

What is an Index in MongoDB?

An index is a special data structure that stores a small portion of the collection’s data in an optimized way. MongoDB uses this structure to quickly locate documents without checking every record one by one.

Without indexes, MongoDB performs a full collection scan, which means it reads every document before returning results. This may work for small datasets, but it becomes slow when your data grows.

Why Indexing is Important

  • Faster queries: Reduces the time needed to find data
  • Better application performance: Improves API response speed
  • Efficient sorting: Helps with sorted query results
  • Scalability: Supports performance even with large data volumes

Default Index in MongoDB

Every MongoDB collection automatically has an index on the _id field. This is why searching by document ID is usually very fast.

javascript db.users.find({ _id: ObjectId("64f123abc456789xyz000111") });

Creating an Index

You can manually create an index on a field that is frequently used in queries.

javascript db.users.createIndex({ email: 1 });

In this example:

  • email is the indexed field
  • 1 means ascending order
  • -1 would mean descending order

How Indexes Improve Queries

Suppose you frequently search users by email:

javascript db.users.find({ email: "rahul@example.com" });

If the email field is indexed, MongoDB can directly find matching documents much faster. Without an index, it has to scan the entire collection.

Types of Indexes in MongoDB

1. Single Field Index

An index created on one field only.

javascript db.users.createIndex({ email: 1 });

2. Compound Index

An index created on multiple fields together.

javascript db.users.createIndex({ name: 1, age: -1 });

Compound indexes are useful when queries often filter or sort by multiple fields.

3. Unique Index

Ensures that duplicate values are not allowed in a field.

javascript db.users.createIndex({ email: 1 }, { unique: true });

This is commonly used for fields like email, username, or phone number.

4. Text Index

Used for text search in string fields.

javascript db.posts.createIndex({ title: "text", content: "text" });

5. TTL Index

Automatically removes documents after a specified time.

javascript db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

TTL indexes are useful for session data, temporary tokens, and logs.

Checking Existing Indexes

You can view all indexes in a collection using:

javascript db.users.getIndexes();

Removing an Index

If an index is no longer needed, you can remove it:

javascript db.users.dropIndex({ email: 1 });

How Indexes Affect Performance

Indexes improve read performance, but they also come with trade-offs.

  • Read operations become faster
  • Write operations may become slightly slower because indexes must also be updated
  • Storage usage increases because indexes take extra space

Because of this, you should create indexes carefully based on actual query patterns.

Using explain() to Analyze Queries

MongoDB provides the explain() method to understand how a query is executed.

javascript db.users.find({ email: "rahul@example.com" }).explain("executionStats");

This helps you check whether MongoDB is using an index or performing a full collection scan.

When to Add an Index

  • Fields used frequently in search queries
  • Fields used in sorting
  • Fields used in filtering large collections
  • Fields used in unique constraints like email or username

When Too Many Indexes Become a Problem

Beginners often think more indexes always mean better performance, but that is not true. Too many indexes can slow down insert, update, and delete operations because MongoDB must maintain all indexes.

The goal is to create only the indexes that support your actual application queries.

Indexing in Mongoose

In Mongoose, you can define indexes directly inside your schema.

javascript const userSchema = new mongoose.Schema({ email: { type: String, unique: true }, name: String });

You can also create compound indexes in Mongoose:

javascript userSchema.index({ name: 1, age: -1 });

Best Practices for Indexing

  • Create indexes based on real query patterns
  • Use unique indexes for unique fields
  • Monitor query performance with explain()
  • Avoid creating unnecessary indexes
  • Review indexes regularly as the application grows

Common Mistakes

  • Not indexing frequently searched fields
  • Adding too many indexes without analysis
  • Ignoring write performance impact
  • Not testing queries with explain()

Real-World Use Cases

  • User login using email or username
  • Searching products by category or name
  • Sorting orders by date
  • Automatic expiration of sessions and OTP records

Conclusion

Indexing is one of the most important techniques for improving MongoDB performance. It helps queries run faster and makes your application more responsive, especially when working with large amounts of data.

However, indexing should be used wisely. A well-planned indexing strategy improves performance, while too many unnecessary indexes can slow down your application. Understanding this balance is essential for building scalable backend systems.

Quick Summary: Indexes improve query performance in MongoDB by helping the database locate data faster, but they should be used carefully to avoid extra write and storage costs.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators