Index Creation Techniques
Basic Index Creation Methods
1. Using createIndex() Method
The primary method for creating indexes in MongoDB is the createIndex()
method.
## Create a single field index
db.collection.createIndex({ fieldName: 1 })
## Create a descending index
db.collection.createIndex({ fieldName: -1 })
2. Unique Indexes
Prevent duplicate values in a specific field.
## Create a unique index
db.users.createIndex({ email: 1 }, { unique: true })
Advanced Index Creation Techniques
Compound Indexes
Create indexes spanning multiple fields.
## Compound index with multiple fields
db.orders.createIndex({
customerId: 1,
orderDate: -1
})
Index Creation Workflow
graph TD
A[Start Index Creation] --> B[Select Collection]
B --> C[Choose Indexing Strategy]
C --> D[Specify Index Fields]
D --> E[Define Index Options]
E --> F[Execute createIndex()]
F --> G[Verify Index Creation]
G --> H[End]
Index Options
Option |
Description |
Example |
unique |
Prevents duplicate values |
{ unique: true } |
sparse |
Only indexes documents with the indexed field |
{ sparse: true } |
background |
Creates index in background |
{ background: true } |
Partial Indexes
Create indexes for a subset of documents.
## Create a partial index
db.restaurants.createIndex(
{ cuisine: 1, name: 1 },
{ partialFilterExpression: { rating: { $gt: 5 } } }
)
Text Indexes
Enable text search capabilities.
## Create a text index
db.articles.createIndex({ content: "text" })
Geospatial Indexes
Support location-based queries.
## Create a 2dsphere index
db.places.createIndex({ location: "2dsphere" })
Practical Considerations with LabEx
When working in LabEx's MongoDB environment, consider:
- Index creation time for large collections
- Performance impact of multiple indexes
- Monitoring index usage and effectiveness
Dropping Indexes
## Remove a specific index
db.collection.dropIndex({ fieldName: 1 })
## Remove all indexes except the default _id index
db.collection.dropIndexes()
Best Practices
- Create indexes that match your query patterns
- Avoid over-indexing
- Monitor index performance
- Use explain() to analyze query execution