Indexes

A query that was instant on 50 orders crawls on 100,000. See why, add an index the way a book adds one, prove the difference with explain(), and choose the right index for a sort, a unique email and a search box.

Updated

Index Basics

  1. Why Queries Get Slow, and What an Index Is (Apprentice): A query with no index reads every document in the collection, which is fine for 50 orders and slow for 100,000, while an index keeps one field's values in order so MongoDB can go straight to the matches, at a cost in disk space and in every write.
  2. Reading explain(): COLLSCAN or IXSCAN (Journeyman): explain with "executionStats" is MongoDB's report on how it ran a query, where the winning plan's stages say whether it read every document (COLLSCAN) or used an index (IXSCAN, then FETCH), and totalDocsExamined against nReturned says how much work each result cost.

Kinds of Indexes

  1. Compound Indexes and the Order of Fields (Journeyman): A compound index keeps its entries in order by one field and then by the next, so a single index can serve a filter and a sort together, and the order of its fields (equal, then sort, then range) decides how much of it MongoDB has to read.
  2. Unique and Text Indexes (Journeyman): A unique index makes MongoDB refuse a second document with the same value, such as a customer's email, with a duplicate key error, and a text index lets a search box find products by the words in their names and descriptions with $text.

Exercise: Fast Order Lookups

  1. Exercise: Fast Order Lookups (Journeyman): Create the four indexes that make Riverbend Bike Shop's slow pages fast and its sign-up form safe, and let the tests read each query's explain report, run the search box and try a duplicate email.

Up Next: MongoDB in an App

  1. Up Next: MongoDB in an App (Journeyman): Look back at the reports and indexes you can build after Module 4, see them work together behind a store's dashboard, and see what Module 5 adds, the same queries running behind a real app's API.