Without an index, MongoDB checks every single document in a collection to answer a query — a collection scan. On a small collection this is instant; on a large one it gets slow fast. An index is a separate, sorted data structure that lets MongoDB jump straight to matching documents instead.
db.users.createIndex({ email: 1 })1 means ascending order, -1 descending — for a single-field index used for equality lookups, the direction rarely matters.
A compound index covers multiple fields, and speeds up queries that filter (or sort) on that combination:
db.users.createIndex({ role: 1, age: -1 })Field order in a compound index matters — this index efficiently serves queries filtering by role alone, or by role and age together, but not a query that filters by age alone.
Add { unique: true } to enforce that no two documents can share a value for that field — commonly used on fields like email:
db.users.createIndex({ email: 1 }, { unique: true }).explain() shows exactly how MongoDB executed a query — look for "stage": "IXSCAN" (index scan, fast) versus "stage": "COLLSCAN" (collection scan, slow on large data):
db.users.find({ email: "ananya@example.com" }).explain()Indexes are a trade-off, not a free upgrade
Indexes speed up reads but slow down writes slightly, since MongoDB has to update every index whenever a document changes. Index the fields you actually query and sort by often — not every field.