Skip to content
MongoDB

Indexes

Create single, compound, and text indexes for performance.

#index#performance#query

Code

mongodb
// Single field index
db.users.createIndex({ email: 1 }, { unique: true });

// Compound index
db.orders.createIndex({ customerId: 1, createdAt: -1 });

// Text index
db.posts.createIndex({ title: "text", body: "text" });
db.posts.find({ $text: { $search: "mongodb tutorial" } });

// List and drop
db.orders.getIndexes();
db.orders.dropIndex("customerId_1_createdAt_-1");

// Explain plan
db.orders.find({ customerId: "c1" }).explain("executionStats");