Sikau

MongoDB · Day 8 · about 25 min

Indexes

Fast queries and unique fields.

Same idea as SQL

Without an index, MongoDB scans every document (COLLSCAN). An index on the fields you filter and sort by lets it jump straight there (IXSCAN). Unique indexes also stop duplicate emails or usernames.

createIndex, unique, explain

print(db.dishes.find({ category: "starter" }).explain().queryPlanner.winningPlan.stage);

db.dishes.createIndex({ category: 1, price: -1 });
printjson(db.dishes.find({ category: "starter" }).explain().queryPlanner.winningPlan);

db.customers.createIndex({ name: 1 }, { unique: true });
try {
  db.customers.insertOne({ name: "Asha", city: "Dharan" });
} catch (e) {
  print(e.message);
}
printjson(db.customers.getIndexes());
  • Index fields you query often; order compound indexes by Equality, Sort, Range (the ESR rule).
  • Indexes cost memory and slow writes — measure with explain("executionStats") on real data.
  • Text search: createIndex({ name: "text" }) and $text (Atlas Search for advanced cases).

The rest of this lesson

  • The ESR ruleexplain
  • Reading executionStatsexplain
  • What happens?predict
  • Read the planmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB