[Case Study] Importance Of Indexing In MongoDB

MongoDB is a document-oriented database that can efficiently handle large amounts of data when indexes are used cleverly. Through this article, I will try to explain how indexes can improve your database queries performance.

What is Indexing in MongoDB?

Indexing in MongoDB is a type of operation that performs virtual storing of elements in some sorted order so that when you search for elements, it can easily go to the stored location and get the results back to you.

How MongoDB Cursor searches the term when the indexing is there vs when the indexing is not there
How MongoDB Cursor searches the term when the indexing is there vs when the indexing is not there

MongoDB Find Query Performance

MongoDB find() is the most used query, that is used to fetch the particular element from database based on the provided condition.

Find Query Performance Without Indexing

find() without indexing takes so much time if there are a large number of documents to iterate in database.

Here I am using 1 million records to run find() query on that and see how much time it takes.

MongoDB find() takes 530 ms to execute when there is no indexing
MongoDB find() takes 530 ms to execute when there is no indexing

It literally takes more than 500 ms to execute a simple query in just 1 million records. This time will go up with the records.

Find Query Performance With Indexing

We have seen how much time it takes to execute a simple find() query if there are no indexes present on the field.

Create an index on the field with the help of the command below-

mongodb create index
mongodb create index

Now we will see how fast it works when there is indexing on the field on which we will use find() query.

Now MongoDB find() takes a few ms to execute the query
Now MongoDB find() takes a few ms to execute the query

Now it takes just a few ms to execute the same query that was taking 530 ms to execute.

Conclusion

Indexes are the most important part of the MongoDB database. They help us execute complex queries on large databases without compromising performance.

Share the article with other MongoDB developers that do not use indexing yet.

Remove duplicate documents from the MongoDB database easily.

Leave a Reply

Your email address will not be published. Required fields are marked *