Indexing
Indexing is a fundamental technique to optimize MongoDB queries. It involves creating data structures that allow for quick retrieval of data. MongoDB supports various types of indexes, including single-field, compound, multi-key, and text indexes. Indexing can significantly boost query performance, especially for frequently accessed fields.
What is indexing?
Indexing is the process of creating data structures that improve the speed of data retrieval operations on a database table. In MongoDB, indexes are created on specific fields to accelerate query execution by reducing the number of documents that need to be scanned.
Types of indexes in MongoDB
MongoDB supports several types of indexes:
- Single-field index: Indexes created on a single field.
- Compound index: Indexes created on multiple fields.
- Multi-key index: Indexes that index the content of arrays.
- Text index: Indexes that support text search.
Creating indexes in MongoDB
Indexes can be created using the createIndex() method:
// Create a single-field index
db.collection.createIndex({ field: 1 });
// Create a compound index
db.collection.createIndex({ field1: 1, field2: -1 });