SyntaxStudy
Sign Up
MongoDB Single Field and Compound Indexes
MongoDB Beginner 1 min read

Single Field and Compound Indexes

Indexes in MongoDB are B-tree data structures that allow the server to locate documents without scanning every document in a collection. Without an index, MongoDB performs a collection scan (COLLSCAN), which is slow for large collections. A single field index on a field you query or sort frequently is the simplest and most common type. Compound indexes cover queries that filter or sort on multiple fields; the order of fields in a compound index matters and follows the Equality, Sort, Range (ESR) rule — put equality fields first, then sort fields, then range fields. Each collection automatically has an index on _id. Indexes consume memory and slow down writes, so you should only create indexes that are actually used by your queries.
Example
// Create a single-field index (ascending)
db.users.createIndex({ email: 1 })

// Unique index — prevents duplicate values
db.users.createIndex({ email: 1 }, { unique: true })

// Compound index — ESR rule: equality, sort, range
db.orders.createIndex({ userId: 1, status: 1, createdAt: -1 })

// Sparse index — only indexes documents where the field exists
db.users.createIndex({ phoneNumber: 1 }, { sparse: true })

// TTL index — automatically deletes documents after N seconds
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

// List all indexes on a collection
db.orders.getIndexes()

// Explain a query — check if index is being used
db.orders.find({ userId: ObjectId("..."), status: "pending" })
  .explain("executionStats")

// Drop an index
db.users.dropIndex({ email: 1 })

// Drop all indexes except _id
db.users.dropIndexes()