How to use indexes properly in MongoDB
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.
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:
We use Docker to start a MongoDB server locally in this post, but you can use a hosted server such as MongoDB Atlas which has a free tier and is a good choice for learning purposes.
When the code above is run, we will have a
laptops collection in the
products database containing 200 documents of laptop data. The documents have content as follows: