Skip to main content
MongoDB Indexing

Indexing & Performance

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e., scan every document in a collection, to select those documents that match the query statement.

Creating an Index

Use createIndex() to create an index on a field.
// Create index on "name" field (ascending)
db.users.createIndex({ name: 1 })

Compound Indexes

You can create an index on multiple fields.
// Index on name (asc) and age (desc)
db.users.createIndex({ name: 1, age: -1 })

Unique Indexes

Ensures that the indexed fields do not store duplicate values.
db.users.createIndex({ email: 1 }, { unique: true })

Viewing Indexes

db.users.getIndexes()

Dropping Indexes

db.users.dropIndex("name_1")

explain()

Use explain() to analyze how MongoDB executes a query.
db.users.find({ name: "Alice" }).explain("executionStats")
Look for:
  • COLLSCAN: Collection Scan (Bad for large datasets).
  • IXSCAN: Index Scan (Good).
  • totalDocsExamined: Number of documents scanned.

Summary

  • Indexes improve read performance but slightly degrade write performance.
  • Always index fields that are frequently used in queries and sorting.
  • Use Compound Indexes for queries that filter on multiple fields.
  • Use explain() to verify that your queries are using indexes.