How to use compound indexes
The beauty of indexes is that they can be used with multiple keys. A single key index can be thought of as a table with one column. A multi-key index or compound index can be visualized as a multi column table where the first column is sorted first, and then the next, and so on. In this recipe, we will look at how to create a compound index and examine how it works.
Getting ready
Load the sample dataset and create an index on the city
field, as described in the previous recipe.
How to do it...
- Assuming you have already created an index on the
city
field, create one by executing the commanddb.mockdata.createIndex({'city': 1})
again. - Run a
find()
query:
> plan = db.mockdata.find({city:'Boston', first_name: 'Sara'}).explain("executionStats")
- Examine the
executionStats
:
> plan['executionStats']
You should see the following result:
{ "executionSuccess" : true, "nReturned" : 1, "executionTimeMillis" : 0, "totalKeysExamined" : 9, "totalDocsExamined" : 9,...