Creating Single-Field and Compound Indexes
Learners will build single-field and compound indexes and observe the query-plan changes with explain('executionStats').
Single-Field Index Basics
A single-field index is the simplest index type: it tracks the values of exactly one document field in a sorted B-tree. You create one with db.collection.createIndex({ field: 1 }), where 1 means ascending order and -1 means descending. Single-field indexes are ideal for queries that filter or sort on just one field.
// Create a single-field ascending index on 'email'
db.users.createIndex({ email: 1 });
// This query now hits the index instead of scanning every document
db.users.find({ email: 'alice@example.com' });Naming Your Indexes
MongoDB auto-generates an index name like email_1 or age_-1 from the field name and direction. You can override this with the name option to give meaningful labels to your indexes—especially helpful when managing many indexes in production or when the auto-generated name would exceed the 127-character limit imposed on compound indexes with many fields.
db.users.createIndex(
{ email: 1 },
{ name: 'idx_users_email' }
);
// List all indexes with their names
db.users.getIndexes();All lessons in this course
- How MongoDB B-Tree Indexes Work
- Creating Single-Field and Compound Indexes
- Index Properties: Unique, Sparse, Partial, TTL
- Reading explain() Output to Diagnose Queries