You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Without indexes, MongoDB performs a collection scan — reading every document to find matches. On large collections this is very slow. Indexes are data structures that store a small, ordered subset of field values, allowing MongoDB to jump directly to the matching documents.
Every collection automatically has a unique index on the _id field. This index is created for you and cannot be dropped.
Use createIndex to add an index on any field:
// Ascending index on the email field
db.users.createIndex({ email: 1 })
// Descending index on createdAt — useful for "latest first" queries
db.articles.createIndex({ createdAt: -1 })
A compound index covers multiple fields. MongoDB can use the index for queries on the leading prefix of the index fields.
// Covers queries filtering by status and sorting by createdAt
db.orders.createIndex({ status: 1, createdAt: -1 })
The order of fields in a compound index matters. Place equality filters first, then range filters, and finally sort fields — this follows the ESR rule (Equality, Sort, Range).
A unique index prevents duplicate values in the indexed field across the collection:
db.users.createIndex({ email: 1 }, { unique: true })
Attempting to insert a document with a duplicate email will now raise a duplicate key error.
A sparse index only indexes documents that contain the indexed field, saving space when the field is optional:
db.users.createIndex({ githubHandle: 1 }, { sparse: true })
A partial index applies an index only to documents matching a filter expression:
// Only index active users
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { status: "active" } }
)
Text indexes support full-text search across string fields:
db.articles.createIndex({ title: "text", body: "text" })
db.articles.find({ $text: { $search: "mongodb aggregation" } })
Use explain to see whether MongoDB is using an index:
db.users.find({ email: "alice@example.com" }).explain("executionStats")
Look for IXSCAN (index scan) in the winning plan. COLLSCAN (collection scan) means no index was used and you should consider adding one.
db.users.getIndexes() // list all indexes
db.users.dropIndex({ email: 1 }) // drop a specific index
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.