createIndex()
Creates an index on specified fields to improve query performance. Essential for production workloads.
Syntax
mongodb
db.collection.createIndex(keys, options)Example
mongodb
// Single field index:
db.users.createIndex({ email: 1 }, { unique: true });
// Compound index:
db.posts.createIndex({ authorId: 1, createdAt: -1 });
// Text index for search:
db.articles.createIndex({ title: "text", body: "text" });
// TTL index (auto-expire documents):
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });