Using indexes efficiently
Creating indexes is a decision that should not be taken lightly. As easy as it is to create indexes via the shell, it can create problems down the line if we end up with too many or with inadequately efficient indexes. In this section, we will learn how to measure the performance of existing indexes, some tips for improving performance, and how we can consolidate the number of indexes so that we have better-performing indexes.
Measuring performance
Learning how to interpret the explain()
command will help you with both optimizing and understanding the performance of an index. The explain()
command, when used in conjunction with a query, will return the query plan that MongoDB would use for this query, instead of the actual results.
It is invoked by chaining it at the end of our query, as follows:
> db.books.find().explain()
It can take three options: queryPlanner
(the default), executionStats
, and allPlansExecution
.
Let’s use the...