Indexes in MongoDB
Indexes in MongoDB improve the speed of queries by allowing the database to find documents more efficiently. Without indexes, MongoDB must scan the entire collection to find matching documents, which can be slow for large datasets.
1. Creating an Index
MongoDB allows you to create indexes on fields to optimize searches.
Example: Creating an Index on the name
Field
db.students.createIndex({ "name": 1 })
Explanation:
1
→ Creates an ascending index (A-Z for strings, low to high for numbers).
Example: Creating a Descending Index
db.students.createIndex({ "age": -1 })
Explanation:
-1
→ Creates a descending index.
2. Viewing Indexes
To check existing indexes in a collection, use:
db.students.getIndexes()
3. Types of Indexes
a) Single Field Index
Indexes a single field to speed up queries.
db.students.createIndex({ "age": 1 })
b) Compound Index
Indexes multiple fields to optimize queries that filter on both fields.
db.students.createIndex({ "name": 1, "age": -1 })
Use Case: When filtering by both name
and age
.
c) Unique Index
Prevents duplicate values in a field.
db.students.createIndex({ "email": 1 }, { unique: true })
d) Text Index
Used for searching text data.
db.students.createIndex({ "description": "text" })
Use Case: Searching for words in a field.
e) TTL Index (Time-To-Live)
Automatically deletes documents after a set time.
db.logs.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
Use Case: Removing old logs after 1 hour.
f) Sparse Index
Only indexes documents that contain the indexed field.
db.students.createIndex({ "phone": 1 }, { sparse: true })
Use Case: When only some documents have a phone
field.
4. Dropping an Index
To remove an index, use:
db.students.dropIndex("name_1")
To remove all indexes:
db.students.dropIndexes()
5. Checking Index Usage
To analyze whether indexes are used in queries:
db.students.explain("executionStats").find({ "name": "Alice" })
Conclusion
Indexes are essential in MongoDB for optimizing query performance. By choosing the right type of index, you can significantly improve the efficiency of data retrieval and enhance overall application performance!