Index basics
Why use indexes?
Without an index, jasonisnthappy must scan every document to find matches. With an index:- Queries on indexed fields are significantly faster
- Unique indexes prevent duplicate values
- Compound indexes support multi-field queries
- Range queries benefit from B-tree structure
Creating indexes
Single-field index
Create an index on a single field.Unique index
Enforce uniqueness constraints with unique indexes.Unique indexes are built on existing data during creation. If duplicates exist, index creation fails.
Compound indexes
Create indexes on multiple fields for multi-criteria queries.- Leftmost prefix rule
- Field order
- Unique compound
Compound indexes follow the leftmost prefix rule:The index can only be used if the query includes the leftmost field(s).
Using indexes
Once created, indexes are used automatically by the query engine.Index-optimized queries
Compound index queries
Managing indexes
List indexes
View all indexes on a collection.Drop an index
Remove an index when it’s no longer needed.Index strategies
Equality queries
Range queries
Indexes optimize range queries on sorted fields.Multi-field queries
Use compound indexes for queries with multiple conditions.Covering indexes
If your query only needs indexed fields, use projection:Index performance
Write performance
Each index adds overhead to insert, update, and delete operations.Read performance
Indexes can improve read performance by orders of magnitude.
Times are approximate for equality queries
Best practices
Index naming conventions
Index maintenance
Common patterns
User lookup by email
Product search by category and price
Unique username/email
Time-based queries
Next steps
Querying
Master the query language
Full-text search
Create text indexes for search
Performance
Optimize database performance
Schema validation
Validate document structure