MongoDB Index
Indexes can generally greatly improve query efficiency. Without an index, MongoDB must scan every file in the collection and select those records that match the query conditions when reading data.
The efficiency of this full-collection scan query is very low, especially when processing large amounts of data. The query may take tens of seconds or even minutes, which is fatal to website performance.
An index is a special data structure. Indexes are 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.
- Compound 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.
- Hash Index: An index that performs hashing on field values.
Create Index
MongoDB uses the createIndex() method to create indexes.
Note that before version 3.0.0, the method for creating indexes was db.collection.ensureIndex(). In later versions, the db.collection.createIndex() method is used. ensureIndex() still works, but it is just an alias of createIndex().
Syntax
The basic syntax format of the createIndex() method is as follows:
db.collection.createIndex( keys, options )
db: Reference to the database.collection: Name of the collection.keys: An object that specifies the field name and the sort order of the index (1 means ascending, -1 means descending).options: An optional parameter that can contain additional options for the index.
The options parameter is an object that can contain multiple configuration options. The following are some commonly used options:
unique: If set totrue, a unique index is created, ensuring that the values of the index field are unique in 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 will automatically generate a name based on the index fields.sparse: If set totrue, create a sparse index that only indexes documents containing the index field.expireAfterSeconds: Sets the expiration time of the index field; MongoDB will automatically delete expired documents.v: Index version, usually no need to set it manually.weights: Specifies weights for a text index.
Example
db.myCollection.createIndex({ age: 1 });
// Create a text index on the name field
db.myCollection.createIndex({ name: "text" });
Example
Index creation:
Example
db.collection.createIndex( { field: 1 }, { unique: true } )
// Create an index running 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 Geospatial Index
For fields that store geographic location data, you can use the 2dsphere or 2d index types to create geospatial indexes.
// 2dsphere index, suitable for spherical geographic data
db.collection.createIndex( { location: "2dsphere" } )
// 2d index, suitable for planar geographic data
db.collection.createIndex( { location: "2d" } )
Create Hash Index
Starting from MongoDB 3.2, you can use hash indexes to hash fields to support large-scale value lookups.
db.collection.createIndex( { field: "hashed" } )View Index
Use the getIndexes() method to view all indexes in a collection:
db.collection.getIndexes()
Delete Index
Use the dropIndex() or dropIndexes() methods to delete indexes:
Example
db.collection.dropIndex( "indexName" )
// Delete all indexes
db.collection.dropIndexes()
Index Strategy
When creating indexes, the following factors need to be considered:
- Query frequency: Fields that are frequently used for querying should be given priority.
- Field cardinality: The higher the cardinality of a field's values (i.e., the more unique values), the better the index effect.
- Index size: The size of the index affects the database's memory usage and query performance.
Index Optimization
When optimizing indexes, the following methods can be considered:
- Choose the appropriate index type: Choose the appropriate index type based on query requirements.
- Create compound indexes: For fields that are often 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, when creating indexes, you need to weigh query performance against write performance.
- Indexes occupy additional storage space, especially for large data sets. The storage cost of indexes needs to be considered.
By designing and using indexes reasonably, you can greatly improve the query performance and response speed of MongoDB databases, thereby better supporting the needs of applications.
Other Extensions