Query Performance
COLLSCAN vs IXSCAN
A collection scan versus an index scan, and the before/after you should be able to show.
COLLSCAN reads every document in the collection and applies the filter. IXSCAN walks index keys, then usually FETCHes the documents those keys point at. The interview before/after is: same query, createIndex, explain again.
db.users.find({ city: "Bangalore" }).explain("executionStats")
// winningPlan.stage: COLLSCAN
// totalDocsExamined: 42 nReturned: 8db.users.createIndex({ city: 1 })
db.users.find({ city: "Bangalore" }).explain("executionStats")
// winningPlan: FETCH → IXSCAN on city_1
// totalKeysExamined: 8 totalDocsExamined: 8 nReturned: 8A COLLSCAN is not always wrong. Forty users, or a query that returns most of the collection ({ isActive: true } at 80%), can be cheaper as a scan than bouncing through a weak index. The planner knows that. Your job is to notice COLLSCAN on a selective filter on a large collection. { $hint: { city: 1 } } forces an index for experiments — not for production defaults.
Interview question
What is the difference between COLLSCAN and IXSCAN?
COLLSCAN reads every document. IXSCAN walks an index and typically FETCHes matching documents. After adding the right index, examined should drop toward nReturned. A COLLSCAN on a tiny collection or an unselective filter can be fine; a COLLSCAN on a selective filter at scale is the bug.
Practice