Indexing in MongoDB is a technique used to improve query performance by organizing data in a way that allows documents to be located quickly. It helps MongoDB retrieve data efficiently without scanning the entire collection.
- Stores data in an ordered structure for faster searching.
- Enhances sorting, filtering, and aggregation operations.
- Improves overall database performance and query efficiency.
Importance of Indexing in MongoDB
Indexing is essential in MongoDB because it speeds up data retrieval and improves query performance. MongoDB provides the createIndex() method to create indexes on specific fields, allowing the database to locate documents more efficiently.
- Improves the performance of find() queries.
- Optimizes range queries using operators such as <, >, <=, and >=.
- Enhances sorting and aggregation operations involving filtering, grouping, and sorting.
Syntax:
db.COLLECTION_NAME.createIndex({ KEY: 1 })Here, KEY represents the field to be indexed, and 1 (ascending) or -1 (descending) specifies the index order.
Creating an Index in MongoDB
MongoDB provides the createIndex() method to create indexes on one or more fields. Indexes help improve query performance by allowing MongoDB to locate documents efficiently without scanning the entire collection.
Syntax:
db.collection.createIndex({ <field>: <1 or -1> });- 1 creates an ascending index.
- -1 creates a descending index.
Example
db.users.createIndex({ username: 1 });- unique: Ensures that indexed values are unique.
- sparse: Indexes only documents that contain the indexed field.
- expireAfterSeconds: Automatically removes documents after a specified time (TTL index).
- hidden: Hides the index from the query planner while keeping it available in the database.
Note: The background option is deprecated in newer MongoDB versions, as indexes are built in the background by default.
Dropping an Indexes in MongoDB
MongoDB provides the dropIndex() and dropIndexes() methods to remove indexes from a collection. Removing unused indexes can help reduce storage usage and improve write performance.
- dropIndex() removes a single index from a collection.
- dropIndexes() removes multiple indexes or all non-default indexes.
- The default _id index cannot be dropped.
Syntax (drop a single index):
db.COLLECTION_NAME.dropIndex({ KEY: 1 })Syntax (drop multiple indexes):
db.COLLECTION_NAME.dropIndexes()Or specify the index names to remove particular indexes, depending on the MongoDB version and usage.
Viewing Indexes in MongoDB
MongoDB provides the getIndexes() method to display all indexes available in a collection. It returns detailed information about each index, including its name, fields, and configuration.
- Lists all indexes created in a collection.
- Displays index keys and their order.
- Helps manage and verify existing indexes.
Syntax:
db.COLLECTION_NAME.getIndexes()This method retrieves the details of all indexes defined for the specified collection.