How to use indexes properly in MongoDB

Boost your MongoDB queries by indexes

Lynn G. Kwong
7 min readMar 14, 2022

An issue we often ignore in MongoDB is the indexes. We may take for granted that MongoDB works like Elasticsearch and all fields are indexed by default. Actually, this is not true! In MongoDB, only the _id field is automatically indexed and we need to build indexes for the fields that are queried frequently to support the queries efficiently. Otherwise, the queries can be very inefficient and will degrade the performance of the MongoDB server.

Image by geralt on Pixabay.

However, indexes come with a cost. While indexes (when properly used) can speed up READ operations dramatically, they will slow down WRITE operations because we need to write indexes for every data record that is inserted or updated. Besides, indexes would need extra storage and RAM for efficient usage which puts extra demand on your infrastructure. Therefore, don’t create MongoDB indexes blindly, and only create them when they are really needed. In this post, we will introduce the basic index types and diagnosis operations in MongoDB, which will give you a clear understanding of what indexes are and how to use them in MongoDB.

We will use the data introduced in the article for advanced MongoDB queries for the demo in this post. You can just download the JSON file and use the following commands to import the data:

--

--

Lynn G. Kwong

I’m a Software Developer (https://medium.com/@lynn-kwong) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.