Indexing & Performance
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e., scan every document in a collection, to select those documents that match the query statement.Creating an Index
UsecreateIndex() to create an index on a field.
Compound Indexes
You can create an index on multiple fields.Unique Indexes
Ensures that the indexed fields do not store duplicate values.Viewing Indexes
Dropping Indexes
explain()
Use explain() to analyze how MongoDB executes a query.
- COLLSCAN: Collection Scan (Bad for large datasets).
- IXSCAN: Index Scan (Good).
- totalDocsExamined: Number of documents scanned.
Summary
- Indexes improve read performance but slightly degrade write performance.
- Always index fields that are frequently used in queries and sorting.
- Use Compound Indexes for queries that filter on multiple fields.
- Use
explain()to verify that your queries are using indexes.