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).