Script Valley
MongoDB: Complete Course
Indexing and Query PerformanceLesson 3.2

How to create single field and compound indexes in MongoDB

createIndex, compound index, index direction, ESR rule, index on nested fields, sparse index, background index builds

Creating indexes with createIndex

Compound index ESR structure

Use createIndex to add an index to any collection. The value 1 specifies ascending order and -1 specifies descending. For single-field equality queries the direction is irrelevant. For sorting and range queries, direction determines whether MongoDB can satisfy the sort using the index or must sort in memory after scanning.

// Single-field unique index — prevents duplicate emails
await db.collection('users').createIndex({ email: 1 }, { unique: true })

// Compound index — field order follows the ESR rule:
// E = Equality fields first, S = Sort fields second, R = Range fields last
await db.collection('orders').createIndex({
  userId: 1,       // E: exact match on userId
  status: 1,       // S: sort output by status
  createdAt: -1    // R: date range queries, most recent first
})

// Sparse index — skip documents where the field is absent
await db.collection('users').createIndex(
  { phoneNumber: 1 },
  { sparse: true }  // documents without phoneNumber are excluded from index
)

// Index a nested field via dot notation
await db.collection('users').createIndex({ 'address.city': 1 })

// List all indexes on a collection
const indexes = await db.collection('orders').indexes()
console.log(indexes)

Why the ESR rule matters

Placing a Range field before the Sort field forces MongoDB to sort results in working memory after the index scan — an in-memory sort stage. This is expensive on large result sets and defeats the purpose of the index covering the sort. Equality first, Sort second, Range last eliminates the in-memory sort.

Up next

MongoDB text indexes and full-text search explained

Sign in to track progress