Blog
{Blog}  See what’s new with MongoDB 6.0 — and why you’ll want to upgrade today >>

MongoDB Indexes Explained

A good indexing strategy is crucial to ensuring that your MongoDB database returns your results in the most efficient way possible. In this article, you will learn what indexes are, how to use them in MongoDB, and how to leverage the MongoDB Atlas Performance Advisor to optimize your queries.

What are Indexes?

An index is a way to organize information so that the database engine can quickly find the relevant results. Think of a file cabinet in a medical office. All the files are usually stored in a specific order, say the last name of patients. If you need to find a patient’s file with the last name starting with “L,” you know precisely in which drawer to look.

Indexes work the same way; they organize the data in a specific order so the engine knows where to look for it. Note that the index doesn’t change the order of the data. Instead, it creates an ordered list that then maps to individual entries.

In that same medical office, if you are looking for all of your patients with a specific prescription, you will need to open each and every file and look at the content. This method of searching could take a long time.

The same goes for a database. Without an index, the database engine needs to go through each record to see if there is a match. Thankfully, with databases, you can add multiple indexes. In this case, you could add a second index on prescriptions, and the database would be much quicker in finding the matching records.

Indexes with MongoDB

Just like traditional databases, MongoDB uses indexes to optimize queries. Any collection in MongoDB can have one or more indexes, and those indexes can be made on one or multiple fields.

Say you have a sales collection, and you want to get the list of documents for the quarter. If you don’t have an index, the database engine will need to go through every record in the database, validate that the date is within the specified range, and add it to the result if it is.

Querying all the documents in a collection is time-consuming and can take up many resources.

An animated image showing the difference between querying data with and without an index.

If you have an index created on the sale date, the database engine will quickly find the first matching document and go through the list until it hits the desired ending date. This is much more efficient than going through each record individually.

You can use the createIndex method with Mongo Shell to create an index.

db.collection.createIndex( <key and index type specification>, <options> )

Index types

There are many types of indexes available in MongoDB. The most common ones are the single field and compound index types. There are more advanced index types that you can use if you deal with arrays, geospatial data, or full-text search. You can find more information about these index types in the documentation.

Single field

Each collection in MongoDB automatically has an index on the _id field. This index can then be used to fetch documents from the database efficiently. However, you will need to query data on other specific fields most of the time. This is where a single field index will come in handy.

Say you want to get the top three sales regularly.

An animated image showing the difference between querying data with and without an index.


A good index here would be on the amount field.

db.collection.createIndex( { amount: 1 });

The top three sales will always be the first three elements in the index, making it much faster than querying the whole collection every time.

Compound index

You can also add a query on multiple fields. Say you wanted to get the top three sales, but on a specific day. Then, adding a compound index that would include both the date and the amount would be the most efficient.

db.collection.createIndex( { date: 1, amount: 1 });

This will create an index where the sales are ordered by date and then by amount.

The ESR rule for index creation

Creating the correct index for the queries is not always obvious. However, there is a general rule that you can use to help you, which is called the ESR (Equality, Sort, Range) rule.

This rule is a thought framework that describes how to build your compound indexes. Start with the fields that use an exact match, add the fields you use for sorting, and, finally, add fields used for non-exact matches (i.e., $lt or $ne operators).

MongoDB Atlas index management

MongoDB Atlas uses the same indexing principles as MongoDB but gives tools to create indexes quickly.

A screenshot of the Create Index modal in the Atlas UI

The Atlas UI provides you with a graphical user interface to create your indexes. You can also add full-text search indexes with Atlas Search.

Index optimization

Another great feature of Atlas is its Performance Advisor. This tool analyzes your frequent queries and suggests new indexes that you could create to increase performance.

A screenshot of the Create Index modal in the Atlas UI


It can also recommend redundant or unused indexes that can otherwise take up some disk space unnecessarily.

You can also analyze your query plans individually using the explain method in the Mongo Shell.

Summary

When a database has performance issues, an easy fix can often be to add the appropriate indexes. These indexes will create a sorted map of your collection to make it easier to retrieve your documents. To find out which indexes you need to create, you should use the ESR rule or the performance advisor in MongoDB Atlas. You can even try it out now for free. Once you start adding the appropriate indexes to your collections, you should be able to see significant improvements in your query performance.

FAQs

What is a MongoDB index?

An index is a sort of map of your collection to make it easier to retrieve your documents. MongoDB can easily find the documents that match your query by listing sorted documents that map to your collection.

Are there indexes in MongoDB?

Yes, MongoDB supports multiple types of indexes. The most common ones are single-field and compound indexes. More advanced index types include multi-key, geospatial, text, and hashed indexes.

Can MongoDB handle millions of records?

Yes, MongoDB is known to support colossal data sets. The key to efficiently querying this data is through a good indexing strategy.