Indexes and explain()
Every collection starts with one index. An index is a sorted list of a field's values, and each value points to its documents. MongoDB uses it to find documents without reading the whole collection:
db.movies.getIndexes()
Output:
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]
This is the index on _id, which is why finding a document by _id is fast. A filter on any other field has to check every document. MongoDB calls this a collection scan, or COLLSCAN. You can see it with .explain(), which describes how MongoDB runs a query. explain returns a large document, so .queryPlanner.winningPlan.stage picks out the one field that names the plan:
db.movies.find(
{ director: "Bong Joon-ho" }
).explain().queryPlanner.winningPlan.stage
Output:
COLLSCAN
With eight movies, a scan is quick. With eight million, it is slow. createIndex() adds an index on a field:
db.movies.createIndex({ director: 1 })
db.movies.getIndexes()
Output:
director_1
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { director: 1 }, name: 'director_1' }
]
The 1 means the index is sorted in ascending order, as in a sort. createIndex returns the name of the new index, director_1, and getIndexes now lists two indexes. Now explain the same query again. This time, look at the whole winningPlan:
db.movies.find(
{ director: "Bong Joon-ho" }
).explain().queryPlanner.winningPlan
Output:
{
isCached: false,
stage: 'FETCH',
inputStage: {
stage: 'IXSCAN',
keyPattern: { director: 1 },
indexName: 'director_1',
isMultiKey: false,
multiKeyPaths: { director: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: { director: [ '["Bong Joon-ho", "Bong Joon-ho"]' ] }
}
}
The inner stage is now IXSCAN, an index scan, using director_1. MongoDB used the index to find the matching documents, and the FETCH stage then read them. You did not change the query. MongoDB chose the index by itself.
Indexes are not free. Every write must also update each index, and indexes take up memory. Add indexes for the fields your queries filter and sort on most, not for every field.
In the exercise, add an index on the year field.