MongoDB Indexes
An index in MongoDB is a data structure used to improve query efficiency, accelerating both read and query operations. MongoDB supports various types of indexes, including single-key indexes, compound indexes, text indexes, geospatial indexes, and more.
The following are common index types in MongoDB:
- Single-Key Index: A single-key index is the simplest type of index; it creates an index on a field within a collection. For example,
db.collection.createIndex({field: 1})creates an ascending index on thefield. - Compound Index: A compound index can create indexes on multiple fields within a collection. For example,
db.collection.createIndex({field1: 1, field2: -1})creates an ascending index onfield1and a descending index onfield2. - Text Index: A text index allows indexing of textual content; it supports tokenization for multiple languages as well as stopword filtering. For example,
db.collection.createIndex({content: "text"})creates a full-text index on thecontentfield. - Geospatial Index: A geospatial index can be created on fields containing geographic coordinates and supports various geospatial query operations. For example,
db.collection.createIndex({location: "2dsphere"})creates a geospatial index on thelocationfield using the 2dsphere method.
Indexes in MongoDB can be created using either the createIndex() or ensureIndex() methods. Creating an index may consume significant system resources and disk space; therefore, it is important to carefully select both the index type and the fields to include. Additionally, MongoDB provides various tools and commands for managing indexes, such as the db.collection.getIndexes() method which can be used to view existing indexes on a collection.