MongoDB Indexing

Mydbops
May 20, 2025
5
Mins to Read
All
MongoDB Indexing
MongoDB Indexing

Make Your MongoDB Queries Faster with Indexing

Indexing is a crucial feature in MongoDB that significantly enhances query performance. Without indexes, MongoDB must perform a collection scan—scanning every document to find matches, which can lead to very slow query execution as data grows.

MongoDB Indexing: Collection Scan vs. Indexed Access Without Index { age: 25 } { age: 35 } { age: 20 } { age: 30 } O(n) find({age: 30}) With Index { age: 25 } { age: 35 } { age: 20 } { age: 30 } Index on "age" field O(log n) find({age: 30})

Indexes are special data structures that store a small portion of the collection’s data in a form that’s quick to traverse. They enable MongoDB to quickly locate and access the data without scanning every document.

Optimize MongoDB Queries with Indexing

What is Indexing in MongoDB?

In simple terms, indexing improves the speed and efficiency of query operations.

Instead of scanning the entire collection, MongoDB uses the index to jump directly to the data you’re looking for.

Indexes are ordered by the value of the field or fields on which the index is created. This ordering helps in:

  • Faster searching
  • Efficient sorting
  • Speeding up range queries and filtering conditions

By default, MongoDB uses prefix compression for all indexes.

MongoDB Indexing

Why is Indexing Important?

When you create an index, you specify:

  • The key (field or fields)
  • The sort order (1 for ascending, -1 for descending)

Indexes dramatically improve the performance of:

  • Find queries (db.collection.find())
  • Range queries (<, >, <=, >=)
  • Sorting operations (sort())
  • Aggregation pipelines involving match, group, or sort stages

How to Create an Index in MongoDB

MongoDB's createIndex() method is used to create indexes.

Syntax

db. collection.createIndex({ field: 1 }, options)

  • field: The field to index
  • 1 or -1: Ascending or descending order

db.getSiblingDB("data") people.createIndex( {name:1},{background:true} )

Common Parameters:

Parameter Type Description
unique Boolean Enforces unique values for the indexed field.
background Boolean Creates the index in the background (non-blocking).
sparse Boolean Only indexes documents containing the specified field.
expireAfterSeconds Integer Sets TTL (Time-to-Live) for documents.
hidden Boolean Hides the index from the query planner without dropping it.

Foreground vs Background Index Builds (Old)

In MongoDB 4.2 and Later

MongoDB 4.2 introduced a hybrid index build process, replacing the older foreground and background methods. Now, index builds are faster and do not require locking the entire database.

Comparison to Foreground and Background Builds

In MongoDB 4.2, index builds lock only the collection being indexed during the start and end of the process to protect metadata changes. The rest of the build allows reads and writes, similar to background builds. Despite this more permissive locking, the index data structure remains efficient.

Key Differences:

  • Foreground: Faster, but blocks all database operations.
  • Background: Slower, but allows reads and writes during the build.

MongoDB Index builds

Current Behaviour (Latest MongoDB Version Index Builds)

  • Locks only at the start and end (for metadata protection).
  • Allows reads and writes during the build process.
  • Index builds are now as efficient as foreground builds.
  • Use db.currentOp() to monitor index build progress.
  • The background option is no longer used.

Performance Insights

  • Foreground builds are still faster.
  • Background builds can take up to 4x longer.
  • With double the data, background builds can be 4x slower.

How to Drop Indexes in MongoDB

In MongoDB, there is a limit of 64 indexes per collection. Exceeding this limit prevents the creation of new indexes. To manage this, it’s essential to clean up unused or duplicate indexes.

You can identify and drop indexes that haven’t been used for more than 50 days, as well as any redundant indexes, to free up space and ensure optimal performance.

You can remove indexes using the dropIndex() or dropIndexes() methods.

  • dropIndex() — Deletes a specific index.

db.collection.dropIndex({ field: 1 })
// or by index name:
db.collection.dropIndex("index_name")

How to View All Indexes

You can view all the indexes on a collection using getIndexes():

db.collection.getIndexes()

Types of Indexes in MongoDB

MongoDB offers various types of indexes to optimise different query patterns:

Single Field Indexes

  • Created on a single field.
  • Sort order is not very important as MongoDB can scan both directions.

Compound Indexes

  • Involve multiple fields.
  • Follow the ESR Rule: Equality, Sort, Range.
  • Field order matters.

Multikey Indexes

  • Automatically created when indexing fields that hold arrays.
  • Each array element is indexed individually.

Text Indexes

  • Enable text search on string content.
  • Can include multiple fields.
  • Support options like:
    • Default language
    • Language override
    • Field weights

Wildcard Indexes

  • Index all fields or fields matching a wildcard pattern.
  • Useful for dynamic schemas with unknown field names.

Geospatial Indexes

  • 2d Indexes: For a flat 2D plane (legacy coordinate pairs).
  • 2dsphere Indexes: For data on an earth-like sphere (latitude/longitude).
  • GeoHaystack Indexes: (Deprecated) for grouping locations in a flat 2D space.

MongoDB Inde types

Index Properties in MongoDB

MongoDB indexes can be customised further using additional properties:

Property Description
Unique Index Ensures no duplicate values.
Sparse Index Indexes only documents where the field exists.
Hidden Index Index exists but is not used in query planning.
TTL Index Automatically removes documents after a time limit.
Partial Index Indexes only documents that match a filter expression.
Case-Insensitive Index Supports case-insensitive string comparisons using collations.

Indexing is a powerful feature that can dramatically improve the performance of queries in MongoDB.

By understanding different types of indexes—single field, compound, multikey, geospatial, text, wildcard—and index options, you can fine-tune your MongoDB database for faster, more efficient data retrieval.

Proper planning and implementation of indexes ensure your MongoDB deployment scales well, handles growing data efficiently, and delivers optimal performance for your applications.

For a more detailed understanding of indexing in MongoDB, we’ve shared several blogs that cover different aspects of the topic. Kindly refer to the following:

  • MongoDB Rule for Indexing (Series 1)  Read here
  • MongoDB Index Type and Properties (Series 2)  Read here
  • Optimise MongoDB Storage: Compression, Indexing, and TTL Best Practices  Read here
  • Mastering MongoDB Hidden Indexes for Optimal Query Performance  Read here
  • Terminate In-Progress Index Builds in MongoDB (Series 3) Read here

Looking to optimize your MongoDB environment? Mydbops offers end-to-end MongoDB solutions including managed services, expert consulting, remote DBA, support, and in-depth performance audits. Whether you're scaling, troubleshooting, or fine-tuning for peak efficiency, our team ensures your MongoDB deployment stays secure, high-performing, and production-ready. Contact us today to get started.

No items found.

About the Author

Subscribe Now!

Subscribe here to get exclusive updates on upcoming webinars, meetups, and to receive instant updates on new database technologies.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.