Creating Indexes
Indexes improve query performance by allowing MongoDB to find documents without scanning the entire collection.
Example
// Create single field index
db.users.createIndex({ email: 1 }) // ascending
db.products.createIndex({ price: -1 }) // descending
// Compound index
db.products.createIndex({ category: 1, price: -1 })
// Unique index
db.users.createIndex({ email: 1 }, { unique: true })
// Text index for search
db.articles.createIndex({ title: "text", content: "text" })
db.articles.find({ $text: { $search: "mongodb tutorial" } })
// List indexes
db.users.getIndexes()
// Drop an index
db.users.dropIndex("email_1") Index Best Practices
Indexes speed up reads but slow down writes. Use them strategically.
- Index fields used in frequent queries and filters
- Index fields used in sort operations
- Compound indexes should match query patterns
- Don't over-index — each index uses memory and slows writes
- Use explain() to analyze query performance
- The _id field is automatically indexed
