Why Indexes Matter
8 min read
Indexes: Making Queries Fast
Without an index, MongoDB performs a collection scan — it reads every document to find matches. On large collections this is slow. An index is a sorted data structure (B-tree) over one or more fields that lets MongoDB jump directly to the matching documents.
MongoDB automatically creates an index on _id. You add your own indexes on fields you frequently query or sort by.
js
// Create a single-field index on name
db.students.createIndex({ name: 1 });
// Compound index: course ascending, age descending
db.students.createIndex({ course: 1, age: -1 });
// Unique index — no two documents can share the same email
db.students.createIndex({ email: 1 }, { unique: true });
// List all indexes on a collection
db.students.getIndexes();Use explain("executionStats") to see whether a query uses an index (IXSCAN) or a full scan (COLLSCAN):
db.students.find({ name: "Aditi" }).explain("executionStats")
Ready to test yourself?
Practice MongoDB— quiz & coding exercises