MongoDB tutorials
7. Indexing – MongoDB tutorials
Video tutorial:
Indexing is a technique that has a primary purpose to speed up the database, take less time to run a query, and return results faster. When you apply an index on some field, MongoDB will store a reference of that document in a separate table that will help to look for those values quickly. Take an example of an index at the end of the book which contains all difficult words and their page number. So instead of looking in the whole book, you can go to the index, find the word and from there you can get its page number. Then you will directly land on that page.
So lets say we have a database where a collection named “companies” has more than 18,000 documents:
Now each query we run on any collection has an execution time which means the time it took the query to run. You can get that using following command:
db.companies.find({ "category_code": "games_video" }).explain("executionStats")
We have a function named explain and in that, we have to send a string parameter having value “executionStats“. This will return a lot of output, you have to search for “executionTimeMillis” inside “executionStats” object:
Now we need to create an index on “category_code” field, its syntax is:
db.companies.createIndex({ "category_code": 1 })
Where companies is the name of collection and category_code is the name of field. Now if you run the above query again, you will see the output:
So you can see how the execution speed oon that field is improved from 16 milliseconds to just 5 milliseconds simply by applying an index.