Indexing
What is an Index?
A sorted structure that turns a collection scan into a targeted read — and costs writes to keep.
Without an index, a filter walks every document (a collection scan). An index is a B-tree of field values pointing at documents. The planner seeks to Bangalore instead of reading Delhi, Pune, and the rest. _id already has a unique index — that is why findOne({ _id }) is cheap.
db.users.createIndex({ city: 1 })
db.users.getIndexes()
db.users.dropIndex({ city: 1 })Every insert, update, and delete that touches an indexed field updates that tree. Indexes you never query are pure write cost plus RAM. The working set — the indexes and documents you actually touch — should fit in memory. If the index is on disk, you traded a scan for a lot of random reads. explain() is how you prove a query uses one; that is the next module.
Interview question
How do indexes work in MongoDB, and why not index every field?
Indexes are B-trees from key values to documents, so a query can seek instead of scanning. Each index is updated on write and should stay in RAM to be useful. Unused indexes cost throughput and memory for no read benefit — audit and drop them.