MongoDB
Beginner
1 min read
Single Field and Compound Indexes
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()