What is an index in MongoDB and how do you check a query uses it?

IntermediateConceptMongoDB
Answer

Short answer

An index lets MongoDB find documents without scanning the whole collection (a COLLSCAN). You create indexes on the fields you filter and sort by, and check with explain("executionStats") that the query shows an IXSCAN and examines roughly as many documents as it returns.

Examples

db.orders.createIndex({ customerId: 1 })
db.orders.createIndex({ customerId: 1, createdAt: -1 })        // compound
db.users.createIndex({ email: 1 }, { unique: true })
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })   // TTL: auto-delete after 1h
db.orders.getIndexes()
db.orders.dropIndex("customerId_1")

Check the plan

db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).explain("executionStats")
// winningPlan.stage: "IXSCAN"   ✅   (COLLSCAN = full scan ❌)
// totalDocsExamined: 48, nReturned: 48   ✅

Compound index rule (ESR)

Order fields as Equality → Sort → Range: { status: 1, createdAt: -1, total: 1 } for status = X, sort by date, total > Y.

What to say in the interview

"Indexes avoid collection scans. I create single, compound, unique or TTL indexes on filter and sort fields, follow the equality-sort-range rule for compound ones, and confirm with explain executionStats that it's an IXSCAN with docs examined close to docs returned."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB