Skip to content

Indexing

What is an Index?

A sorted structure that turns a collection scan into a targeted read — and costs writes to keep.

BeginnerAbout 5 minutes

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 })
Create, list, drop. 1 is ascending, -1 descending.

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?

Think about it first.