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
Insert & Find
Insert documents and query a collection.
Query Operators
Use comparison, logical, array, and regex operators.
Aggregation Pipeline
Build multi-stage pipelines for analytics.
Update & Delete
Modify and remove documents with update operators.
Collections & Schema
Manage collections, validators, and capped collections.
Replica Set
Configure a replica set for high availability.