MongoDB Indexing
MongoDB Indexing Best Practices: Performance Tips & Tricks
Introduction
Performance is one of the most important considerations when building applications with MongoDB. As an application grows, its database may need to handle millions of documents, complex queries, frequent updates, and thousands of concurrent requests. Without proper optimization, even a well-designed MongoDB database can experience slow queries, increased CPU usage, and unnecessary disk I/O.
One of the most effective ways to improve MongoDB performance is indexing.
Indexes help MongoDB locate the documents that match a query without scanning an entire collection. When designed correctly, indexes can significantly reduce query execution time, improve sorting performance, and make applications more responsive. However, creating too many indexes or choosing the wrong index structure can increase storage consumption and slow down write operations.
The goal is not to create an index for every field. Instead, it is to create the right indexes for your application’s actual query patterns.
In this blog, we will explore how MongoDB indexes work, the different types of indexes, practical indexing best practices, common mistakes, and techniques for identifying and resolving query performance problems.
1. What Is Indexing in MongoDB?
An index in MongoDB is a data structure that stores information about selected fields in a collection and helps the database locate matching documents efficiently.
Consider an employees collection containing thousands of documents:
{
_id: ObjectId("..."),
name: "Rahul Sharma",
department: "IT",
salary: 75000,
location: "Pune"
}
Suppose an application frequently retrieves employees from the IT department:
db.employees.find({
department: "IT"
})
Without a suitable index, MongoDB may need to examine every document in the collection to identify matching employees. This operation is called a collection scan, represented as COLLSCAN in query execution plans.
You can create an index on the department field:
db.employees.createIndex({
department: 1
})
Now MongoDB can use the index to locate documents that match the query, potentially examining far fewer documents.
The value 1 specifies ascending index order, while -1 specifies descending index order. For a single-field equality query, either direction can generally support the same lookup efficiently. Direction becomes more important for compound indexes and sorting.
Key takeaway: Indexes can improve read performance, but their effectiveness depends on query patterns, field selectivity, data distribution, and the cost of maintaining the index during writes.
2. How MongoDB Indexes Work
MongoDB uses B-tree-based index structures to organize indexed values and references to the corresponding documents. The index allows MongoDB to navigate to relevant entries instead of examining every document.
When a query runs, MongoDB’s query planner evaluates available query plans and selects a plan it estimates will be efficient. Depending on the query and available indexes, MongoDB may use an index scan (IXSCAN), fetch documents from the collection, or perform a collection scan.
For example:
db.orders.find({
customerId: 101
})
If an appropriate index exists on customerId, MongoDB may locate the matching index entries and retrieve the corresponding order documents.
Without a suitable index, it may have to scan a much larger portion of the collection.
However, an index does not guarantee that a query will be fast. A query that matches a large percentage of a collection, returns many large documents, or requires an expensive sort may still be costly.
This is why indexing should always be combined with query analysis and application-level performance testing.
3. Types of Indexes in MongoDB
MongoDB provides several index types, each designed for different access patterns. Choosing the right type is essential for achieving optimal performance.
3.1 Single-Field Index
A single-field index is created on one field. It is useful when applications frequently filter, sort, or retrieve documents using that field.
Example:
db.products.createIndex({
category: 1
})
This index can help queries such as:
db.products.find({
category: "Electronics"
})
Best use cases:
- Filtering by a frequently queried field.
- Sorting on a single indexed field.
- Supporting common equality queries.
- Optimizing simple lookup operations.
Avoid creating indexes on fields that are rarely queried unless there is another clear operational reason.
3.2 Compound Index
A compound index contains multiple fields. It is especially useful when queries filter or sort using a combination of fields.
Example:
db.orders.createIndex({
customerId: 1,
status: 1,
createdAt: -1
})
This index is designed for queries such as:
db.orders.find({
customerId: 101,
status: "Completed"
}).sort({
createdAt: -1
})
The index orders entries by customerId, then by status within each customer, and finally by createdAt within the preceding field values.
Compound indexes follow the prefix principle: an index on { customerId: 1, status: 1, createdAt: -1 } can generally support queries using customerId alone, or customerId and status together. It is not equally suitable for every query that references only status or createdAt.
Best practice: Design compound indexes around your most important combinations of equality filters, range conditions, and sorting requirements.
3.3 Multikey Index
MongoDB automatically creates a multikey index when an indexed field contains an array.
Example document:
{
name: "Wireless Headphones",
tags: ["audio", "wireless", "electronics"]
}
Create an index:
db.products.createIndex({
tags: 1
})
MongoDB can use this index to find documents containing a specific array element:
db.products.find({
tags: "wireless"
})
Multikey indexes are useful for tags, product attributes, categories, and other array-based fields.
However, array indexing has additional constraints. For example, a compound multikey index generally cannot index two independent array fields in the same document. Large arrays can also increase index size and write overhead.
3.4 Text Index
Text indexes support text search across string fields.
Example:
db.articles.createIndex({
title: "text",
content: "text"
})
You can search for matching text:
db.articles.find({
$text: {
$search: "MongoDB performance"
}
})
Text indexes can help with basic keyword-search requirements. For more advanced search features, such as sophisticated relevance tuning, autocomplete, or richer linguistic capabilities, evaluate MongoDB Search or another dedicated search solution.
A standard text index has specific restrictions, including limitations on the number of text indexes per collection.
3.5 Geospatial Index
Geospatial indexes support queries involving geographic coordinates and location-based calculations.
For example, a collection may contain:
{
name: "Coffee Shop",
location: {
type: "Point",
coordinates: [73.8567, 18.5204]
}
}
Create a 2dsphere index:
db.places.createIndex({
location: "2dsphere"
})
You can then perform geospatial queries, such as finding places within a specified distance.
Geospatial indexing is useful for delivery applications, location-based services, nearby-store searches, and travel platforms.
3.6 Unique Index
A unique index prevents duplicate values in the indexed field or combination of fields.
Example:
db.users.createIndex(
{ email: 1 },
{ unique: true }
)
This ensures that duplicate indexed email values cannot be inserted.
Unique indexes are valuable for enforcing business rules, such as unique usernames, email addresses, and external transaction identifiers.
Before creating a unique index, verify that existing data does not contain duplicates. Also consider how missing fields and null values are handled, because a unique single-field index has specific constraints on those values.
3.7 Partial Index
A partial index includes only documents that satisfy a specified filter expression.
Example:
db.orders.createIndex(
{ customerId: 1, createdAt: -1 },
{
partialFilterExpression: {
status: "Pending"
}
}
)
This index contains entries only for orders with a Pending status.
Partial indexes can reduce index size and maintenance overhead when queries frequently target a specific subset of documents.
For MongoDB to use a partial index safely, the query generally needs to include conditions that ensure the results are covered by the partial filter.
3.8 TTL Index
A Time-To-Live (TTL) index allows MongoDB to automatically remove documents after a configured period or at a specified expiration time.
For example:
db.sessions.createIndex(
{ expiresAt: 1 },
{ expireAfterSeconds: 0 }
)
If a session contains an expiresAt date, MongoDB can automatically delete it after that time has passed.
TTL indexes are useful for temporary sessions, expiring tokens, and short-lived records.
Important: TTL deletion is performed asynchronously by a background process. Documents are not guaranteed to disappear at the exact expiration second, so TTL indexes should not replace application-level authorization or strict expiration checks.
4. Follow the ESR Rule for Compound Indexes
One of the most useful MongoDB indexing techniques is the ESR rule: Equality, Sort, Range.
It provides a starting point for deciding the field order in a compound index.
- Equality: Fields tested for exact values.
- Sort: Fields used to order results.
- Range: Fields queried using conditions such as
$gt,$lt,$gte, or$lte.
Consider this query:
db.orders.find({
customerId: 101,
status: "Completed",
total: { $gte: 5000 }
}).sort({
createdAt: -1
})
A possible index is:
db.orders.createIndex({
customerId: 1,
status: 1,
createdAt: -1,
total: 1
})
Here, customerId and status are equality fields, createdAt is the sort field, and total is the range field.
Putting sort before range can help MongoDB produce sorted results directly from the index, potentially avoiding an in-memory sort. However, placing a selective range field earlier may be preferable in some workloads if reducing the number of examined entries matters more than avoiding a sort.
Therefore, ESR is a design guideline, not an absolute rule. Benchmark alternative index orders against realistic data and query patterns.
5. Create Indexes Based on Real Query Patterns
One of the most common indexing mistakes is creating indexes based on assumptions rather than actual application behavior.
Before creating an index, understand how the application accesses data.
Ask the following questions:
- Which fields appear most frequently in query filters?
- Which fields are used for sorting?
- Which queries return large numbers of documents?
- Which queries run frequently or have high latency?
- Which queries are important to application response times?
- How frequently are the indexed fields updated?
For example, an e-commerce application may frequently execute these queries:
db.products.find({
category: "Electronics"
})
db.orders.find({
customerId: 101,
status: "Pending"
}).sort({
createdAt: -1
})
db.users.find({
email: "[email protected]"
})
Potential indexes include:
db.products.createIndex({
category: 1
})
db.orders.createIndex({
customerId: 1,
status: 1,
createdAt: -1
})
db.users.createIndex({
email: 1
}, {
unique: true
})
These indexes serve specific query patterns rather than indexing every field in the database.
As requirements evolve, periodically review query statistics and remove indexes that no longer provide sufficient value.
6. Use explain() to Analyze Query Performance
Creating an index is only the first step. You must verify that MongoDB actually uses it and that it improves performance.
MongoDB’s explain() method provides details about query planning and execution.
Example:
db.orders.find({
customerId: 101,
status: "Completed"
}).explain("executionStats")
Important fields include:
| Field | Meaning |
|---|---|
winningPlan |
The query plan selected by MongoDB. |
stage |
The execution stage, such as IXSCAN or COLLSCAN. |
nReturned |
Number of documents returned. |
totalDocsExamined |
Number of collection documents examined. |
totalKeysExamined |
Number of index entries examined. |
executionTimeMillis |
Reported execution time for that explain run. |
What should you look for?
1. COLLSCAN
This indicates a collection scan in the reported plan. It can be a warning sign for large collections, but it is not always bad. MongoDB may correctly choose a collection scan when a query returns a large proportion of the collection.
2. IXSCAN
This indicates that the plan scans an index. It is often desirable for selective queries, but an index scan can still examine many entries and perform poorly.
3. High totalDocsExamined
If MongoDB examines many documents to return only a few results, investigate whether a better index or more selective query could reduce the work.
4. High totalKeysExamined
A high number of examined index entries relative to the number of results may indicate a broad index scan, a poorly matched index, or a query that naturally requires many matches.
5. In-memory sorting
Look for a SORT stage in the winning plan. Depending on the query and execution engine, it may indicate that MongoDB could not satisfy the requested sort directly from an index.
For example, if a query returns 20 documents but examines 50,000 documents, the ratio is worth investigating. However, ratios are diagnostic clues rather than universal performance targets.
Best practice: Compare execution plans before and after an index change, using representative data and repeated measurements. Do not judge performance from a single execution-time value alone.
7. Avoid Over-Indexing
Indexes improve many read operations, but every additional index has a cost.
When documents are inserted, deleted, or updated, MongoDB may need to maintain the relevant indexes. A collection with many unnecessary indexes can consume additional storage, memory, and write-processing resources.
For example, suppose a collection has indexes on:
{ customerId: 1 }
{ status: 1 }
{ createdAt: -1 }
{ customerId: 1, status: 1 }
{ customerId: 1, status: 1, createdAt: -1 }
Some of these indexes may be useful, but others may provide overlapping benefits. The compound index can support certain queries that use its prefix fields, making separate indexes potentially redundant.
However, do not assume every overlapping index is unnecessary. A shorter index may consume less memory, support a different sort direction or query shape, or provide better performance for a particular workload.
To inspect indexes:
db.orders.getIndexes()
To remove a confirmed unnecessary index:
db.orders.dropIndex("status_1")
Replace the example name with the actual index name returned by getIndexes().
Before dropping an index, check its usage, query patterns, uniqueness constraints, and operational importance. In production, monitor the impact of index changes and follow a safe rollout process.
8. Understand the Trade-Off Between Read and Write Performance
Indexing is a balancing act.
Consider an application that receives millions of writes daily. Adding indexes to many fields may improve certain reads but increase the work required for inserts and updates.
For example:
db.products.createIndex({
brand: 1
})
db.products.createIndex({
price: 1
})
db.products.createIndex({
category: 1,
price: -1
})
These indexes may help different product searches. However, each additional index increases storage requirements and may add maintenance work when indexed fields change.
To optimize a write-heavy application:
- Identify indexes that support essential queries.
- Remove indexes that have no meaningful benefit.
- Avoid indexing fields that change frequently unless the read-performance benefit justifies the cost.
- Measure insert, update, and delete throughput after index changes.
- Test with a representative mix of reads and writes.
Do not sacrifice important query performance merely to minimize index count. The objective is to optimize the complete workload, not just one operation type.
9. Use Covered Queries Where Appropriate
A covered query is one that MongoDB can satisfy entirely from an index without fetching the matching documents from the collection.
Suppose the application needs only customerId and createdAt:
db.orders.find(
{ customerId: 101 },
{ _id: 0, customerId: 1, createdAt: 1 }
)
A suitable index is:
db.orders.createIndex({
customerId: 1,
createdAt: 1
})
If the query’s filter and projected fields are supported by the index, MongoDB may be able to return the results directly from index entries.
The _id field is included by default in projections unless explicitly excluded. Because this example excludes _id, the index does not need to contain it for the intended projection.
Covered queries can reduce document fetches and disk access, especially for frequently executed queries that return small sets of fields.
However, including too many fields in an index can make it larger and more expensive to maintain. Use covered queries strategically rather than creating very wide indexes for every projection.
10. Use Partial Indexes to Reduce Index Size
Partial indexes can be particularly useful when an application repeatedly queries only a subset of its documents.
Suppose an orders collection contains millions of records, but the dashboard mostly displays pending orders.
Create a partial index:
db.orders.createIndex(
{ customerId: 1, createdAt: -1 },
{
partialFilterExpression: {
status: "Pending"
}
}
)
This index stores entries only for documents whose status is "Pending".
A matching query could be:
db.orders.find({
status: "Pending",
customerId: 101
}).sort({
createdAt: -1
})
Because the query includes the partial filter condition, MongoDB can potentially use the index without excluding valid results.
Partial indexes can be valuable for active records, open tickets, unpublished content, and other workflows where most queries target a clearly defined subset.
11. Use Sparse Indexes Carefully
A sparse index includes documents that contain the indexed field, rather than indexing every document.
Example:
db.users.createIndex(
{ secondaryEmail: 1 },
{ sparse: true }
)
This may be appropriate when many documents do not contain secondaryEmail.
However, sparse indexes have limitations. For example, they do not include documents where the indexed field is missing, so they may not support queries that need to return both documents with and without that field.
For many use cases, a partial index offers more explicit control over which documents are included.
Choose sparse indexing only when its inclusion rules match your query requirements. Also remember that sparse and unique options can interact in ways that affect how missing values are handled.
12. Be Careful With Low-Cardinality Fields
Cardinality refers to the number of distinct values in a field.
For example:
emailoften has high cardinality.countrymay have moderate cardinality.statuswith values such asPending,Completed, andCancelledhas relatively low cardinality.
An index on a low-cardinality field may be less selective because many documents share the same value.
For example:
db.orders.createIndex({
status: 1
})
This index may be useful if queries often select a small subset of statuses. But if nearly every document is returned for a common status, MongoDB may decide that scanning the collection is more efficient.
Low-cardinality fields can still be valuable components of compound indexes:
db.orders.createIndex({
customerId: 1,
status: 1
})
Here, customerId may narrow the results substantially before the status condition is applied.
Tip: Evaluate field selectivity in the context of the complete query. Do not reject an index simply because one field has few distinct values.
13. Indexes and Sorting: Avoid Unnecessary Sort Operations
Sorting large result sets can be expensive when MongoDB cannot obtain the requested order directly from an index.
Consider:
db.products.find({
category: "Electronics"
}).sort({
price: -1
})
A compound index can support the filter and sort:
db.products.createIndex({
category: 1,
price: -1
})
This index may allow MongoDB to find products in the selected category and return them in descending price order without a separate in-memory sort.
Compound index sort direction matters. An index can generally support the specified sort direction or its complete inverse, but mixed sort patterns must align with the index’s field directions.
For example, an index on { a: 1, b: -1 } can support { a: 1, b: -1 } and the inverse { a: -1, b: 1 }, subject to the query’s equality-prefix requirements.
Always validate sorting behavior with explain("executionStats").
14. Use Index Hints Only When Necessary
MongoDB normally selects an execution plan automatically. In some cases, developers may want to test a specific index using hint().
Example:
db.orders.find({
customerId: 101
}).hint({
customerId: 1
})
A hint can help with controlled testing, diagnosing query-planner decisions, or addressing a known issue.
However, forcing an index can be harmful when data distributions or query patterns change. The forced index may become less efficient than the plan MongoDB would otherwise select.
Use hints only when you understand the workload and have benchmark evidence. Avoid treating hints as a substitute for proper index design.
15. Monitor Index Usage and Database Performance
Indexing should be an ongoing process rather than a one-time configuration.
MongoDB provides commands and diagnostic tools that help administrators understand index usage and query performance.
List existing indexes
db.orders.getIndexes()
This shows the indexes defined on a collection, including their key patterns and options.
Inspect index statistics
db.orders.aggregate([
{ $indexStats: {} }
])
The $indexStats aggregation stage provides usage statistics for indexes on the collection.
These statistics can help identify indexes that appear to be rarely used. However, they reflect the observation period and relevant server or node context. An index with low observed usage may still be necessary for infrequent reports, maintenance tasks, or specific business operations.
Inspect collection statistics
db.orders.stats()
Collection statistics can provide information about document counts, storage, and index sizes.
Review slow queries
Use the database profiler, diagnostic logs, or monitoring features appropriate to your MongoDB deployment to investigate slow queries.
Be mindful that enabling profiling can introduce overhead, especially when configured to capture all operations. In production, select an appropriate profiling level and retention strategy.
For managed MongoDB deployments, monitoring dashboards and query-analysis features may also help identify expensive operations and index opportunities.
16. Indexing Best Practices for Large Collections
When collections grow into millions or billions of documents, index design becomes increasingly important.
Consider these strategies:
1. Prioritize high-impact queries. Focus first on frequent or latency-sensitive queries that examine too many documents or index entries.
2. Keep indexes as small as practical. Smaller indexes can reduce storage usage and may be more likely to fit in memory.
3. Use compound indexes strategically. A well-designed compound index may support multiple related query patterns, but verify each important pattern separately.
4. Avoid unnecessary fields in indexes. Wider indexes consume more storage and increase maintenance work.
5. Benchmark with production-like data. Small test collections may not reveal the behavior seen with real data distributions.
6. Monitor memory and storage pressure. If frequently accessed index pages do not fit comfortably in memory, performance may be affected by disk reads.
7. Plan index creation carefully. Building indexes on large collections can consume CPU, memory, and disk resources. Follow the deployment’s documented index-build procedures and monitor resource usage.
8. Reevaluate indexes as the application evolves. A new API endpoint or changed query pattern may require a different index strategy.
17. Indexing in Sharded MongoDB Clusters
In a sharded cluster, index design must account for data distribution and the shard key.
Indexes on shard-key fields play an important role in shard targeting and cluster operations. Queries that include the shard key appropriately may be routed to a subset of shards, while queries that do not may need to contact multiple shards.
For example, suppose orders are sharded using customerId as the shard key. A query such as:
db.orders.find({
customerId: 101,
status: "Completed"
})
may be targeted more efficiently than a query that filters only on status, depending on the actual shard-key configuration and query routing.
An index that is efficient on each individual shard does not automatically eliminate the cost of scatter-gather queries across multiple shards.
When designing indexes for sharded deployments:
- Understand the shard key and its distribution.
- Review whether important queries target specific shards.
- Create indexes that support local filtering and sorting on each shard.
- Monitor shard-level query performance and data skew.
- Consider the effects of index creation and maintenance across the cluster.
Sharding and indexing solve related but different problems: sharding distributes data and workload, while indexes improve access to data within the relevant collections.
18. Common MongoDB Indexing Mistakes
Even experienced developers can make indexing decisions that hurt performance.
Mistake 1: Indexing Every Field
More indexes do not automatically mean faster queries. Excessive indexes consume resources and increase write overhead.
Solution: Create indexes based on measured query requirements.
Mistake 2: Ignoring Compound Index Field Order
A compound index may not support a query efficiently when the query does not use its leading fields appropriately.
Solution: Analyze equality filters, sort patterns, range predicates, and the compound index prefix.
Mistake 3: Assuming IXSCAN Always Means Good Performance
A query may scan millions of index entries and still be slow.
Solution: Review totalKeysExamined, totalDocsExamined, the winning plan, and the actual workload.
Mistake 4: Forgetting Write Performance
Every additional index can increase the cost of writes.
Solution: Measure both read and write performance after index changes.
Mistake 5: Ignoring Data Distribution
An index that works well on test data may perform poorly when most production documents share the same field value.
Solution: Test with representative data volumes and distributions.
Mistake 6: Forcing Indexes Without Evidence
A manually selected index may become inefficient as data changes.
Solution: Prefer the query planner unless controlled testing demonstrates a reason to use a hint.
Mistake 7: Dropping Indexes Based on a Short Observation Period
An index may support infrequent but critical operations.
Solution: Review usage over a suitable period and verify application requirements before removal.
19. Practical Example: Optimizing a Slow Orders Query
Consider an orders collection with several million documents.
An application frequently executes:
db.orders.find({
customerId: 501,
status: "Completed"
}).sort({
createdAt: -1
}).limit(20)
Without an appropriate index, MongoDB may need to scan many documents and sort the matching results.
Step 1: Analyze the query
db.orders.find({
customerId: 501,
status: "Completed"
}).sort({
createdAt: -1
}).limit(20).explain("executionStats")
Review the winning plan and the numbers of documents and index entries examined.
Step 2: Create a compound index
db.orders.createIndex({
customerId: 1,
status: 1,
createdAt: -1
})
The index places equality fields first and the sorting field afterward.
Step 3: Run the query again
Repeat the same query and inspect the execution statistics.
Look for evidence that MongoDB can use an index scan, avoid an unnecessary sort, and examine fewer documents or index entries.
Step 4: Compare results
Compare the before-and-after execution plans, latency under repeated runs, CPU usage, and write overhead.
Do not assume a specific speed improvement in advance. The actual result depends on the collection size, selectivity, data distribution, cache state, and other workload conditions.
Step 5: Validate the broader workload
Check whether the new index benefits the target query without creating unacceptable write or storage costs.
This approach makes indexing a measurable optimization rather than a guess.
20. A Practical MongoDB Indexing Checklist
Before deploying an index to production, review the following checklist:
-
Identify the query pattern the index is intended to improve.
-
Confirm that the query is important enough to justify the index.
-
Review equality filters, sort fields, and range conditions.
-
Consider compound index prefixes and sort directions.
-
Test the query using
explain("executionStats"). -
Check
totalDocsExaminedandtotalKeysExamined. -
Verify whether an index can eliminate a costly sort or document fetch.
-
Evaluate the index’s storage and write-maintenance costs.
-
Review existing indexes for overlap.
-
Test against representative data and concurrent workload.
-
Monitor performance after deployment.
-
Reassess indexes when query patterns change.
Conclusion
MongoDB indexing is one of the most effective ways to improve database query performance, but successful indexing requires more than creating indexes on frequently used fields.
The best results come from understanding application query patterns, selecting appropriate index types, designing compound indexes carefully, and validating every important change with execution statistics.
Techniques such as the ESR rule, partial indexes, covered queries, and index-usage monitoring can help reduce unnecessary database work. At the same time, avoiding over-indexing protects write performance, storage capacity, and operational efficiency.
Remember: the best index is not the one that indexes the most fields. It is the one that delivers measurable performance benefits for your actual workload.
As your application evolves, review your queries and indexes regularly. A disciplined, evidence-based indexing strategy helps MongoDB applications remain responsive, scalable, and reliable as data volumes grow.
If you want to strengthen your MongoDB skills, practice analyzing query plans, building compound indexes, and comparing performance before and after optimization. These practical skills are valuable for developers, database administrators, and performance engineers working with modern data-driven applications.

