Indexes speed queries and enforce uniqueness. Default _id index exists on every collection.
Single-field index
db.orders.createIndex({ customerId: 1 })
db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.getIndexes()Practice: Run on practice in mongosh.
Unique index
db.users.createIndex({ email: 1 }, { unique: true })
Explain recap
db.orders.find({ customerId: 'c-42' }).explain('executionStats')Look for IXSCAN vs COLLSCAN and totalDocsExamined.
Important interview questions and answers
- Q: Index trade-off?
A: Faster reads, slower writes and more disk. - Q: Compound index order?
A: Equality fields first, then sort range—matches query shape.
Self-check
- Create index on email unique.
- What does COLLSCAN mean?
Tip: Index foreign keys used in $lookup and frequent find filters.
Interview prep
- COLLSCAN?
- Full collection scan—slow on large data without index.
- Unique index?
- Enforces uniqueness on indexed field(s).