Skip to main content
Indexes dramatically improve query performance by allowing the database to quickly locate documents without scanning the entire collection.

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
Indexes speed up reads but add overhead to writes. Only index fields you query frequently.

Creating indexes

Single-field index

Create an index on a single field.
Index names must be unique within a collection. Use descriptive names like field_idx or field_unique_idx.

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.
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.
Dropping an index is immediate and cannot be undone. Queries using that index will fall back to collection scans.

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.
Best practice: Only create indexes you actually use. Remove unused indexes to improve write performance.

Read performance

Indexes can improve read performance by orders of magnitude. Times are approximate for equality queries

Best practices

Create indexes on:
  • Fields used in WHERE clauses (query filters)
  • Fields used for sorting
  • Fields used for uniqueness constraints
  • Foreign key-like fields (user_id, product_id, etc.)
Avoid indexing:
  • Fields that are rarely queried
  • Fields with very low cardinality (e.g., boolean fields)
  • Very large text fields (use text indexes instead)
  • Fields that change frequently if you rarely query them

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