Back to journal

    Developer journal

    MongoDB Indexing Explained: How Indexes Improve Query Performance

    Learn how MongoDB indexes work, explore different index types, design efficient compound indexes using the ESR guideline, and measure query performance with explain().

    13 min read29 sections
    MongoDB Indexing Explained: How Indexes Improve Query Performance article cover
    In this article29 sectionsBrowse sections
    13 min read · 2,552 words

    MongoDB Indexing Explained: How Indexes Improve Query Performance

    As an application grows, its database grows with it. A query that works perfectly with a few hundred documents might become noticeably slower when the collection contains hundreds of thousands or even millions of records.

    One of the most important techniques for improving MongoDB query performance is indexing.

    Indexes help MongoDB find documents without examining every document in a collection. However, creating indexes without understanding your application's query patterns can introduce unnecessary storage costs and slow down write operations.

    In this guide, we'll explore how MongoDB indexes work, when to create them, the different index types, how to design compound indexes, and how to measure their effectiveness using practical examples.

    We'll use an orders collection throughout the article to demonstrate these concepts.

    1. What Is a MongoDB Index?

    An index is a separate data structure that stores information about selected fields in a collection. It helps MongoDB locate matching documents more efficiently.

    Think about a book with an index at the end. Instead of reading every page to find a particular topic, you can look up the topic in the index and jump directly to the relevant pages.

    MongoDB indexes work with a similar principle.

    Consider an orders collection containing documents like these:

    {
      _id: ObjectId("..."),
      userId: ObjectId("..."),
      status: "delivered",
      total: 1499,
      createdAt: ISODate("2026-11-20T10:00:00Z")
    }
    

    Suppose your application frequently runs this query:

    db.orders.find({
      userId: ObjectId("...")
    });
    

    Without a suitable index, MongoDB may need to examine every document in the collection to find matching orders. This is called a collection scan.

    You can create an index on userId:

    db.orders.createIndex({ userId: 1 });
    

    MongoDB can then use the index to locate matching records rather than scanning the entire collection.

    The 1 represents ascending index order, while -1 represents descending index order.

    For a single-field index, ascending and descending order generally provide the same filtering capability. Sort direction becomes more important when designing compound indexes.

    2. How Do MongoDB Indexes Work?

    MongoDB uses B-tree-based index structures for its standard indexes.

    Conceptually, an index maintains ordered values and references to the corresponding documents. This allows MongoDB to navigate the index to find matching values instead of examining every document.

    There are two important query execution stages to understand:

    • COLLSCAN: MongoDB scans documents in the collection.
    • IXSCAN: MongoDB scans an index to find matching index entries.

    Consider the following query:

    db.orders.find({
      status: "delivered"
    });
    

    If no suitable index exists, MongoDB may use a collection scan.

    You can inspect the query execution plan:

    db.orders
      .find({ status: "delivered" })
      .explain("executionStats");
    

    Now create an index:

    db.orders.createIndex({ status: 1 });
    

    Run the same query again:

    db.orders
      .find({ status: "delivered" })
      .explain("executionStats");
    

    Depending on the collection size, data distribution, and query selectivity, MongoDB may choose to use the new index.

    Important: An index does not guarantee that every query will use it. MongoDB's query planner chooses an execution plan based on the query and available indexes.

    3. Different Types of MongoDB Indexes

    MongoDB supports several index types. Each one is designed for particular data structures and query requirements.

    3.1 Single-Field Index

    A single-field index indexes one field in a document.

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

    This is useful when your application frequently searches using one field.

    For example:

    db.users.findOne({
      email: "[email protected]"
    });
    

    Common use cases include:

    • Looking up users by email.
    • Searching orders by status.
    • Finding products by SKU.
    • Filtering records by creation date.

    MongoDB automatically creates a unique index on the _id field when a collection is created.

    3.2 Compound Index

    A compound index contains multiple fields in a specific order.

    Consider an application that frequently retrieves a user's orders filtered by status and sorted by creation date:

    db.orders.find({
      userId: ObjectId("..."),
      status: "delivered"
    }).sort({
      createdAt: -1
    });
    

    You can create a compound index:

    db.orders.createIndex({
      userId: 1,
      status: 1,
      createdAt: -1
    });
    

    This index is designed around the fields used by the query.

    The order of fields matters because compound indexes support queries on their leading fields, also called index prefixes.

    For example, this index:

    {
      userId: 1,
      status: 1,
      createdAt: -1
    }
    

    Can support queries using:

    • userId
    • userId and status
    • userId, status, and createdAt

    However, it is not an equivalent replacement for an index that starts with status when your query only filters by status.

    This is why compound indexes should be designed around actual query patterns rather than simply combining every commonly used field.

    3.3 Multikey Index

    A multikey index is used when a field contains an array.

    Consider a product document:

    {
      name: "Gaming Laptop",
      categories: ["electronics", "computers", "gaming"]
    }
    

    You can create an index on the array field:

    db.products.createIndex({
      categories: 1
    });
    

    MongoDB creates index entries for the array values.

    This helps queries such as:

    db.products.find({
      categories: "gaming"
    });
    

    Multikey indexes are useful for:

    • Product categories.
    • Tags.
    • User interests.
    • Array-based permissions.
    • Embedded array data.

    Be careful when designing compound multikey indexes. MongoDB has restrictions on indexing multiple array fields in the same document within one compound multikey index.

    3.4 Text Index

    Text indexes support text search on string fields.

    For example:

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

    You can then search for text:

    db.articles.find({
      $text: {
        $search: "mongodb indexing"
      }
    });
    

    Text indexes can be useful for basic keyword-search functionality.

    However, they are not a replacement for a dedicated search solution when you need advanced relevance tuning, autocomplete, complex linguistic features, or sophisticated search experiences.

    3.5 Geospatial Index

    Geospatial indexes support location-based queries.

    MongoDB provides two main geospatial index types:

    • 2dsphere for spherical geometry and Earth-like geographic coordinates.
    • 2d for planar geometry.

    For example, a location document might look like this:

    {
      name: "Restaurant A",
      location: {
        type: "Point",
        coordinates: [76.2673, 9.9312]
      }
    }
    

    Create a geospatial index:

    db.places.createIndex({
      location: "2dsphere"
    });
    

    You can use geospatial queries to find nearby locations, locations within an area, and other spatial relationships.

    3.6 Hashed Index

    A hashed index stores hashed values of a field.

    db.users.createIndex({
      userId: "hashed"
    });
    

    Hashed indexes are commonly used with equality-based queries and can be useful in certain sharding strategies.

    They are not suitable for range queries or sorting by the original field.

    3.7 TTL Index

    A Time To Live (TTL) index automatically removes documents after a specified period.

    For example, imagine an application that stores temporary verification codes:

    {
      email: "[email protected]",
      code: "123456",
      createdAt: new Date()
    }
    

    Create a TTL index:

    db.verificationCodes.createIndex(
      { createdAt: 1 },
      { expireAfterSeconds: 300 }
    );
    

    MongoDB automatically removes expired documents in the background.

    TTL indexes are useful for:

    • OTP records.
    • Temporary sessions.
    • Expiring tokens.
    • Temporary logs.
    • Short-lived cache records.

    TTL deletion is asynchronous, so documents are not guaranteed to disappear at the exact expiration second.

    3.8 Wildcard Index

    A wildcard index can support queries against fields whose names are not known in advance.

    db.products.createIndex({
      "$**": 1
    });
    

    This can be useful for flexible document structures where different documents contain different dynamic fields.

    However, wildcard indexes are not automatically the best solution for every flexible schema. Targeted indexes are usually preferable when your query patterns are known.

    4. How to Design Compound Indexes Using the ESR Guideline

    One of the most important concepts in MongoDB index design is the ESR guideline.

    ESR stands for:

    • E — Equality
    • S — Sort
    • R — Range

    It provides a useful starting point for arranging fields in compound indexes.

    Let's understand it with an example.

    Suppose your application retrieves recent delivered orders for a specific user:

    db.orders.find({
      userId: ObjectId("..."),
      status: "delivered",
      total: { $gte: 1000 }
    }).sort({
      createdAt: -1
    });
    

    The query contains:

    • Equality: userId, status
    • Sort: createdAt
    • Range: total

    Following the ESR guideline, an index could be:

    db.orders.createIndex({
      userId: 1,
      status: 1,
      createdAt: -1,
      total: 1
    });
    

    The equality fields come first, followed by the sort field and then the range field.

    Why does the order matter?

    Compound indexes store their fields in the order specified when the index is created.

    That ordering determines which query patterns the index can support efficiently.

    For example, an index beginning with userId can support queries that filter by userId, including queries that also filter by subsequent indexed fields.

    But an index beginning with createdAt is not an equivalent choice for a query that only filters by userId.

    ESR versus ERS

    ESR is a guideline, not an absolute rule.

    Sometimes a range condition is highly selective and filtering it earlier can be more efficient than preserving index order for sorting.

    In those cases, the ERS arrangement may be worth testing:

    db.orders.createIndex({
      userId: 1,
      status: 1,
      total: 1,
      createdAt: -1
    });
    

    The right choice depends on your data distribution, query patterns, and whether avoiding an in-memory sort is important.

    Always measure both designs with representative data before deciding.

    5. How to Analyze Query Performance with explain()

    Creating an index is only part of the job. You also need to verify whether MongoDB is using it effectively.

    The explain() method provides information about query execution plans and execution statistics.

    Example:

    db.orders
      .find({
        userId: ObjectId("..."),
        status: "delivered"
      })
      .explain("executionStats");
    

    Pay attention to these fields:

    FieldMeaning
    nReturnedNumber of documents returned
    totalKeysExaminedNumber of index keys examined
    totalDocsExaminedNumber of documents examined
    executionTimeMillisExecution time reported for the operation

    Understanding the results

    Suppose a query returns 100 documents.

    Example A — Inefficient scan

    {
      nReturned: 100,
      totalKeysExamined: 0,
      totalDocsExamined: 50000
    }
    

    This suggests MongoDB examined 50,000 documents to return 100 results.

    Example B — More targeted index scan

    {
      nReturned: 100,
      totalKeysExamined: 100,
      totalDocsExamined: 100
    }
    

    This example shows a more targeted execution pattern.

    These are illustrative numbers, not benchmark results. Actual results depend on your collection, indexes, data distribution, and query.

    Important execution stages

    • COLLSCAN: A collection scan.
    • IXSCAN: An index scan.
    • FETCH: MongoDB retrieves the matching documents after an index scan.
    • SORT: A sort stage appears when MongoDB needs to perform a separate sort operation.

    A FETCH stage is not necessarily a problem. Many normal indexed queries need to retrieve full documents after locating them through an index.

    A covered query is a special case where MongoDB can satisfy the query using the index itself without fetching documents from the collection.

    Do not judge performance using only the presence of IXSCAN. Compare the number of examined keys and documents, the returned results, and execution behavior under representative workloads.

    6. Using Indexes with Mongoose

    If you are building MERN applications, you will likely use Mongoose to interact with MongoDB.

    Mongoose allows you to define indexes directly in your schemas.

    For example:

    import mongoose from "mongoose";
    
    const orderSchema = new mongoose.Schema({
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        required: true
      },
    
      status: {
        type: String,
        required: true
      },
    
      total: {
        type: Number,
        required: true
      },
    
      createdAt: {
        type: Date,
        default: Date.now
      }
    });
    

    Define a compound index:

    orderSchema.index({
      userId: 1,
      status: 1,
      createdAt: -1
    });
    

    Create the model:

    const Order = mongoose.model("Order", orderSchema);
    
    export default Order;
    

    Mongoose will use the schema's index definitions when indexes are built.

    Creating indexes explicitly

    For production applications, you may prefer to manage index creation through controlled deployment or database migration scripts.

    For example:

    await Order.collection.createIndex({
      userId: 1,
      status: 1,
      createdAt: -1
    });
    

    This gives you explicit control over when the index is created.

    Avoid blindly rebuilding indexes during every application startup. Coordinate index changes with your deployment process, especially for large collections.

    7. Common MongoDB Indexing Mistakes

    Indexes can improve read performance, but poor index design can create new problems.

    Here are some mistakes to avoid.

    7.1 Creating indexes on every field

    More indexes do not automatically mean better performance.

    Every index consumes storage and must be maintained when documents are inserted, updated, or deleted.

    Create indexes for meaningful query patterns rather than indexing every field.

    7.2 Ignoring compound index field order

    An index on:

    {
      userId: 1,
      status: 1
    }
    

    is not interchangeable with:

    {
      status: 1,
      userId: 1
    }
    

    The order affects which query patterns can use the index efficiently.

    7.3 Creating redundant indexes

    Suppose you already have:

    db.orders.createIndex({
      userId: 1,
      status: 1
    });
    

    Creating another identical index provides no useful benefit.

    Some indexes that appear redundant may still be necessary because of differences in uniqueness, sparsity, or other index options. Review those properties before removing anything.

    7.4 Ignoring write performance

    Indexes are not free.

    When an indexed field changes, MongoDB needs to maintain the corresponding index entries.

    Applications with heavy write workloads should carefully evaluate how many indexes they actually need.

    7.5 Never reviewing unused indexes

    An index that was useful six months ago might no longer support your current application queries.

    MongoDB provides index usage statistics through $indexStats:

    db.orders.aggregate([
      {
        $indexStats: {}
      }
    ]);
    

    Use these statistics as one input when identifying potentially unused indexes. Review the observation period and application workload before dropping anything.

    8. MongoDB Indexing Best Practices for Production

    When designing indexes for production applications, keep these practices in mind:

    1. Understand your queries first. Identify the filters, sorting, and projections used by your application.
    2. Prioritize frequent queries. Index patterns that are used regularly and affect application performance.
    3. Use compound indexes carefully. Design them around actual query combinations and field ordering.
    4. Follow ESR as a starting point. Test ERS when a selective range condition makes it worthwhile.
    5. Measure with explain(). Review execution statistics instead of assuming an index improved performance.
    6. Avoid unnecessary indexes. Consider the storage and write costs of every index.
    7. Review index usage periodically. Remove genuinely unnecessary indexes after checking their constraints and workload.
    8. Manage production index changes deliberately. Use a controlled deployment or migration process.
    9. Test with realistic data. A query that performs well with a small development dataset may behave differently at production scale.
    10. Monitor both reads and writes. Database optimization should consider the complete workload, not just read speed.

    Conclusion

    MongoDB indexing is one of the most important tools for building applications that remain responsive as their data grows.

    Understanding index types, compound index ordering, the ESR guideline, and query execution statistics helps you make better database design decisions.

    However, the goal should not be to create as many indexes as possible. It should be to create the right indexes for the queries your application actually performs.

    Start by identifying your most frequent and expensive queries, create indexes that support those patterns, and measure the results using explain("executionStats").

    Remember: Good indexing starts with understanding your application's queries, not with blindly adding indexes.

    Further Reading

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal