CodeToLive

MongoDB Indexes & Performance

Optimize query performance with proper indexing strategies.

Single Field Index

// Create ascending index on the "name" field
db.users.createIndex({ name: 1 })

// Create descending index on the "age" field
db.users.createIndex({ age: -1 })

Compound Index

// Create compound index on multiple fields
db.users.createIndex({ name: 1, age: -1 })

Order of fields matters for sorting and query coverage.

Multikey Index (Array)

// Index on array field
db.products.createIndex({ tags: 1 })

Automatically created when indexing an array field.

Text Index

// Create text index for full-text search
db.articles.createIndex({ content: "text" })

// Text search query
db.articles.find({ $text: { $search: "mongodb tutorial" } })

Index Properties

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

// TTL index (auto-delete after time)
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

// Partial index
db.users.createIndex(
  { name: 1 },
  { partialFilterExpression: { age: { $gt: 18 } } }
)

Index Management

// List all indexes
db.collection.getIndexes()

// Remove index
db.collection.dropIndex("name_1")

// Analyze query performance
db.collection.explain().find({ name: "Alice" })
← Back to Tutorials