What is an Index
An index is a separate, physical data structure that stores sorted values of one or more columns in a database table.
How Indexes Work
- Quickly locate records with specific values
- Avoid full table scans
- Greatly improve query efficiency
Index Types Explained
1. Single Field Index
db.users.createIndex({"username": 1})
TTL Index:
db.logs.createIndex({"createdAt": 1}, {expireAfterSeconds: 3600})
2. Compound Index
Compound indexes follow the leftmost prefix principle:
db.collection.createIndex({ "field1": 1, "field2": -1 })
3. Multi-Key Index
Specifically optimized for queries on array fields:
db.products.createIndex({tags: 1})
4. Geospatial Index
- 2dsphere index: For spherical geographic coordinates
- 2d index: For planar coordinates
5. Text Index
db.collection.createIndex({"content": "text"})
6. Hashed Index
db.users.createIndex({"username": "hashed"})
Hashed indexes only support exact match queries and do not support range queries.
MongoDB Default Indexes
MongoDB automatically creates a unique index on the _id field when a collection is created.