Single Field, Compound, and Multikey Indexes

Indexing Fundamentals

Without indexes, MongoDB must scan every document in a collection to satisfy a query — a collection scan. Indexes dramatically speed up queries by letting MongoDB jump directly to matching documents, much like a book's index.

1. The Default _id Index

Every collection automatically gets a unique index on _id — you never need to create this one manually.

2. Single Field Indexes

// Create an ascending index on "email"
db.users.createIndex({ email: 1 })

// Create a unique index (prevents duplicate emails)
db.users.createIndex({ email: 1 }, { unique: true })

// View all indexes on a collection
db.users.getIndexes()

3. Compound Indexes

Compound indexes cover queries filtering or sorting on multiple fields — but field order matters.

db.orders.createIndex({ customerId: 1, orderDate: -1 })

// Efficient — uses the compound index
db.orders.find({ customerId: ObjectId("...") }).sort({ orderDate: -1 })

// Less efficient — can't use the index for orderDate alone
db.orders.find({ orderDate: { $gt: ISODate("2026-01-01") } })
ESR Rule: When designing compound indexes, order fields as EqualitySortRange for optimal performance.

4. Multikey Indexes

When you index a field that holds an array, MongoDB automatically creates a multikey index — indexing each array element individually.

db.products.createIndex({ tags: 1 })

// Matches any product whose tags array contains "electronics"
db.products.find({ tags: "electronics" })

5. Analyzing Query Performance

db.orders.find({ customerId: ObjectId("...") }).explain("executionStats")
Explain FieldMeaning
COLLSCANFull collection scan — no index used (bad for large collections)
IXSCANIndex scan used — efficient
nReturnedNumber of documents returned
totalDocsExaminedDocuments scanned — should be close to nReturned

6. Indexing Fundamentals Checklist

  • ✅ Understand the default _id index
  • ✅ Create single field and unique indexes
  • ✅ Apply the ESR rule for compound indexes
  • ✅ Recognize multikey indexes on array fields
  • ✅ Use explain() to verify index usage
Key Takeaway: Indexes are the single biggest lever for query performance in MongoDB. Always index fields used in filters, sorts, and joins — but avoid over-indexing, since every index adds write overhead.

Ready to master MongoDB?

Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.

Explore Course