Index Creation Methods
Overview of Index Creation in MongoDB
MongoDB provides multiple methods to create indexes, each suited to different scenarios and use cases. Understanding these methods helps optimize database performance with LabEx's practical approach.
1. createIndex() Method
The primary method for creating indexes in MongoDB.
## Basic syntax
db.collection.createIndex({ fieldName: 1 })
## Example: Create an ascending index on username
db.users.createIndex({ username: 1 })
2. Unique Indexes
Prevent duplicate values in indexed fields.
## Create a unique index
db.users.createIndex({ email: 1 }, { unique: true })
3. Compound Indexes
Index multiple fields together.
## Compound index on multiple fields
db.products.createIndex({ category: 1, price: -1 })
Index Creation Options
Option |
Description |
Example |
unique |
Prevents duplicate values |
{ unique: true } |
sparse |
Only indexes documents with the field |
{ sparse: true } |
background |
Creates index in background |
{ background: true } |
4. Partial Indexes
Create indexes for a subset of documents.
## Index only active users
db.users.createIndex(
{ email: 1 },
{
partialFilterExpression: {
status: "active"
}
}
)
5. Text Indexes
Enable text search capabilities.
## Create a text index
db.articles.createIndex({ content: "text" })
6. Geospatial Indexes
Support location-based queries.
## Create a 2dsphere index for geographic data
db.locations.createIndex({ location: "2dsphere" })
Mermaid Visualization of Index Creation Process
graph TD
A[Start] --> B[Select Collection]
B --> C[Choose Index Fields]
C --> D[Select Index Type]
D --> E[Create Index]
E --> F[Verify Index Creation]
Best Practices with LabEx
- Analyze query patterns before creating indexes
- Monitor index performance
- Remove unused indexes
- Use explain() to understand query execution
Checking Existing Indexes
## List all indexes in a collection
db.collection.getIndexes()
By mastering these index creation methods, you'll optimize MongoDB performance and enhance your database design skills with LabEx's comprehensive learning approach.