Without an index, MongoDB performs a collection scan (COLLSCAN) — it reads every document. An index is a B-tree of sorted key values with pointers to documents, so lookups become tree traversals: O(log n) instead of O(n).
Creating indexes
createIndex takes a key pattern: 1 ascending, -1 descending. Direction matters only for compound sorts.
db.users.createIndex({ email: 1 }, { unique: true })
db.products.createIndex({ category: 1, price: -1 })
db.products.getIndexes()Reading explain()
Append .explain() to see the plan. IXSCAN = index used; COLLSCAN = full scan. Compare totalDocsExamined to nReturned: a big gap means wasted work. Try this live in the index visualizer.
db.products.find({ category: "electronics" }).explain()
// winningPlan.stage: "IXSCAN", indexName: "category_1"The cost of indexes
Every index slows down writes (each insert/update must also update the B-tree) and consumes RAM. Index what you query — and nothing more.