MongoDB Indexes
Indexes can usually greatly improve query efficiency. Without indexes, MongoDB must scan every document in a collection when reading data and select those records that match the query conditions.
This kind of query that scans the whole collection is very inefficient, especially when dealing with large amounts of data, where a query may take tens of seconds or even minutes, which is very fatal to website performance.
An index is a special data structure. An index is stored in a data collection that is easy to traverse and read. An index is a structure that sorts the values of one or more columns in a database table.
In MongoDB, common index types include:
- Single field index: An index based on a single field.
- Composite index: An index based on a combination of multiple fields.
- Text index: Used to support full-text search.
- Geospatial index: Used for querying geospatial data.
- Hashed index: An index that hashes field values.
Creating indexes
MongoDB uses the createIndex() method to create indexes.
Note that before version 3.0.0, the index creation method was db.collection.ensureIndex(), and later versions use the db.collection.createIndex() method; ensureIndex() can still be used, but is only an alias for createIndex().
Syntax
The basic syntax of the createIndex() method is as follows:
db.collection.createIndex( keys, options )
db: A reference to the database.collection: The name of the collection.keys: An object that specifies the field name and the sort direction of the index (1 for ascending, -1 for descending).options: An optional parameter that can contain additional options for the index.
The options parameter is an object that can contain various configuration options. The following are some commonly used options:
unique: If set totrue, creates a unique index, ensuring that the values of the indexed field are unique within the collection.background: If set totrue, the index creation process runs in the background without affecting other database operations.name: Specifies the name of the index. If not specified, MongoDB automatically generates a name based on the indexed fields.sparse: If set totrue, creates a sparse index that only indexes documents containing the indexed field.expireAfterSeconds: Sets the expiration time for the indexed field, after which MongoDB automatically deletes expired documents.v: The index version, which usually does not need to be set manually.weights: Specifies weights for a text index.
Example
// Create an ascending index on the age field
db.
myCollection
.
createIndex
(
{
age
:
1
}
)
;
// Create a text index on the name field
db.
myCollection
.
createIndex
(
{
name
:
"text"
}
)
;
Example
Index creation:
Example
// Create a unique index
db.
collection
.
createIndex
(
{
field
:
1
}
,
{
unique
:
true
}
)
// Create an index that runs in the background
db.
collection
.
createIndex
(
{
field
:
1
}
,
{
background
:
true
}
)
// Create a sparse index
db.
collection
.
createIndex
(
{
field
:
1
}
,
{
sparse
:
true
}
)
// Create a text index and specify weights
db.
collection
.
createIndex
(
{
field
:
"text"
}
,
{
weights
:
{
field
:
10
}
}
)
Create a geospatial index
For fields that store geographic location data, you can use the 2dsphere or 2d index type to create a geospatial index.
// 2dsphere index, suitable for spherical geospatial data
db.
collection
.
createIndex
(
{
location
:
"2dsphere"
}
)
// 2d index, suitable for planar geospatial data
db.
collection
.
createIndex
(
{
location
:
"2d"
}
)
Create a hashed index
Starting from MongoDB 3.2, you can use hashed indexes to hash a field in order to support lookups over a wide range of values.
db.collection.createIndex( { field: "hashed" } )
View indexes
Use the getIndexes() method to view all indexes in a collection:
db.collection.getIndexes()
Delete indexes
Use the dropIndex() or dropIndexes() method to delete indexes:
Example
// Delete a specified index
db.
collection
.
dropIndex
(
"indexName"
)
// Delete all indexes
db.
collection
.
dropIndexes
(
)
Indexing strategies
When creating indexes, you need to consider the following factors:
- Query frequency: Give priority to fields that are frequently used in queries.
- Field cardinality: The higher the cardinality of the field values (that is, the more unique values), the more effective the index.
- Index size: The size of the index affects the database's memory usage and query performance.
Index optimization
When optimizing indexes, you can consider the following approaches:
- Choose the right index type: Choose the appropriate index type based on query requirements.
- Create compound indexes: For fields that are frequently used together, consider creating a compound index to improve query efficiency.
- Monitor index performance: Regularly monitor index usage and adjust indexes according to actual needs.
Notes
- Although indexes can improve query performance, they also increase the overhead of write operations. Therefore, you need to balance query performance against write performance when creating indexes.
- Indexes consume additional storage space, especially for large datasets, so you need to consider the storage cost of indexes.
By designing and using indexes properly, you can greatly improve the query performance and response speed of a MongoDB database, thereby better supporting the needs of your application.