Skip to content
MongoDB

Indexes

Create single, compound, and text indexes for performance.

By EZ4Code Team
indexperformancequery

Code

// 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");

Explanation

Indexes speed up queries but slow down writes and consume disk; create them based on real query patterns. Compound indexes support prefix queries, so order fields by equality, sort, and range. explain reveals whether a query uses an index or performs a collection scan.

More MongoDB Snippets