Indexing in MongoDB — MongoDB Technical Interview Questions & Answers

Speeding up queries with single-field and compound indexes.

Indexing in MongoDB

  • Simple meaning: An index is a sorted helper so MongoDB does not scan every document to find roll: 12.
  • How to use: db.students.createIndex({ roll: 1 }) — 1 means ascending. Compound: { city: 1, marks: -1 }.
  • Every collection already has an index on _id.
  • Check: db.students.find({ roll: 12 }).explain("executionStats") — look for IXSCAN, not COLLSCAN.
  • Common mistake: indexing every field. Writes get slower. Index what you filter and sort on.
  • Interview tip: Speeds reads, costs writes. Default _id index. Show createIndex + explain.

Technical Interview Tip: Index the filter fields. Prove with explain().

Code Examples for Indexing in MongoDB

Indexing in MongoDB — working example

db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ city: 1, age: -1 })
db.users.getIndexes()

Indexing in MongoDB — indexes speed reads; unique indexes also enforce constraints. Compound indexes support multi-field filters/sorts.

How to Explain Indexing in MongoDB to an Interviewer

How do you speed up find({ roll: 12 })?

createIndex({ roll: 1 }) Confirm with explain()