6 min read
•Question 5 of 27mediumWhat are indexes in MongoDB?
Understanding MongoDB indexing.
What You'll Learn
- What indexes are
- Types of indexes
- Creating and managing indexes
What are Indexes?
Indexes improve query performance by allowing MongoDB to find documents without scanning every document in a collection.
Types of Indexes
Single Field Index
code.jsJavaScript
db.users.createIndex({ email: 1 }); // Ascending
db.users.createIndex({ age: -1 }); // DescendingCompound Index
code.jsJavaScript
db.users.createIndex({ lastName: 1, firstName: 1 });Unique Index
code.jsJavaScript
db.users.createIndex({ email: 1 }, { unique: true });Text Index
code.jsJavaScript
db.articles.createIndex({ content: "text" });
db.articles.find({ $text: { $search: "mongodb tutorial" } });TTL Index (Auto-expire)
code.jsJavaScript
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });Managing Indexes
code.jsJavaScript
// List all indexes
db.users.getIndexes();
// Drop index
db.users.dropIndex("email_1");
// Drop all indexes (except _id)
db.users.dropIndexes();Explain Query Performance
code.jsJavaScript
db.users.find({ email: "john@example.com" }).explain("executionStats");
// Check "totalDocsExamined" vs "nReturned"Best Practices
- Index fields used in queries and sorting
- Avoid over-indexing (slows writes)
- Use compound indexes for multi-field queries
- Monitor index usage with explain()