MongoDB indexes
In MongoDB, indexes are used to improve the performance of queries by allowing the database to quickly find and retrieve the data that matches query conditions. Here’s an overview of the types of indexes MongoDB supports:
1. Single Field Index
- Definition: An index on a single field in a document.
- Usage: It's the simplest and most common type of index. You create a single field index to quickly locate documents based on that field.
- Example:
This creates an ascending index on thedb.collection.createIndex({ "age": 1 });
age
field. Queries involving theage
field will be faster.
2. Compound Index
- Definition: An index on multiple fields in a document. The order of the fields in a compound index is important because it affects how MongoDB can optimize the queries.
- Usage: Compound indexes are useful when you query based on multiple fields.
- Example:
This creates an index on bothdb.collection.createIndex({ "lastName": 1, "firstName": 1 });
lastName
andfirstName
in ascending order, optimizing queries that involve both fields or just thelastName
.
3. Multikey Index
- Definition: An index on fields that contain arrays. MongoDB automatically creates a multikey index if you index a field with array values.
- Usage: Multikey indexes allow queries to match on individual array elements.
- Example:
This creates an index on thedb.collection.createIndex({ "tags": 1 });
tags
field, which might contain arrays like["tech", "science"]
. The index allows efficient querying of documents that match any of the array elements.
4. Text Index
- Definition: A specialized index for string fields to support text search within the database.
- Usage: Text indexes enable full-text search capabilities in MongoDB, allowing you to search for words or phrases in string fields.
- Example:
This creates a text index on thedb.collection.createIndex({ "description": "text" });
description
field, enabling queries like searching for specific keywords within text.
5. Geospatial Index
- Definition: Indexes for supporting location-based queries like proximity searches, distance calculations, or geospatial operations.
- Types:
- 2d Index: For flat (planar) surface searches.
- 2dsphere Index: For spherical geometry, which is used in most geospatial searches like finding nearby places on Earth.
- Usage: Enables efficient querying of geospatial data, such as finding nearby locations within a certain radius.
- Example:
This creates a 2dsphere index on thedb.collection.createIndex({ "location": "2dsphere" });
location
field to perform geospatial queries like finding points within a geographic area.