1.Why indexes exist
Without an index, a query checks every document in the collection — a collection scan. An index is a sorted structure on one or more fields that lets MongoDB jump straight to matching values instead of checking each document in turn.
Key features
- No index → COLLSCAN: every document in the collection is checked against the query
- An index → IXSCAN: MongoDB walks a sorted structure and jumps to matching values
- Indexes are B-trees, so they support equality, range, and sorted-order queries efficiently
- Every collection has one index by default: a unique index on _id
- An index costs write performance — every insert/update to an indexed field also updates the index
Scan vs. index, at a glance
- no index — COLLSCAN — check every document
- createIndex — a sorted structure
- IXSCAN — jump to matches
Command
db.<collection>.createIndex({ <field>: 1 }) // 1 = ascending, -1 = descendingNo index means a collection scan (COLLSCAN) — every document checked. An index (IXSCAN) lets MongoDB jump to matches, at the cost of extra work on every write.