Skip to the workspace
Pebellslearn by building
Creating Indexes  ›  Lesson

Single Field Indexes

Single Field 12 minAn index is a sorted list of one field's values pointing back to documents, so queries on that field examine only matching entries instead of scanning the whole collection, at the cost of extra work on every write.

mongodb / Single Field Indexes

Explore each scene at your own pace.

01 · The rule

The rule

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 _id already, 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 }) and sort({ 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.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.