Single Field Indexes
With five books, any query is instant. With two million, find({ author: "Jane Austen" }) has to open every single document to check its author. An index is the book-shop equivalent of an alphabetical author shelf: go straight to "A", read along, stop.
The rule
Index the field you filter on; turn COLLSCAN into IXSCAN.
db.books.createIndex({ author: 1 }) // 1 ascending, -1 descending
db.books.getIndexes() // _id_ and author_1
db.books.find({ author: "Jane Austen" }).explain("executionStats")- An index stores the field's values in sorted order, each pointing to its document.
- Every collection has an index on
_idalready, created automatically and not removable. - For a single field, direction (1 or -1) does not matter: MongoDB can walk the index either way, so it serves
sort({ author: 1 })andsort({ author: -1 })alike. - An index on an array field (a multikey index) gets one entry per element, so
{ genres: 1 }helps{ genres: "classic" }. { unique: true }makes the index reject duplicates:createIndex({ isbn: 1 }, { unique: true }).- Every index costs: inserts, updates and deletes must also update it, and it uses disk and memory. Index what you query, not everything.