Optimization Techniques
1. Indexing Techniques
graph LR
A[Indexing] --> B[Single Field Index]
A --> C[Compound Index]
A --> D[Multikey Index]
A --> E[Text Index]
Index Creation Example
// Create single field index
db.collection.createIndex({ username: 1 })
// Create compound index
db.collection.createIndex({ lastName: 1, firstName: 1 })
2. Query Optimization
Optimization Technique |
Description |
Impact |
Selective Projection |
Retrieve only necessary fields |
Reduces network overhead |
Query Hint |
Force specific index usage |
Improves query performance |
Aggregation Pipeline |
Efficient data processing |
Minimizes client-side processing |
3. Memory Configuration
## Adjust WiredTiger cache size
sudo nano /etc/mongod.conf
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4 ## Allocate appropriate memory
4. Sharding Configuration
graph TD
A[Sharding Cluster] --> B[Config Servers]
A --> C[Shard Servers]
A --> D[Mongos Router]
Sharding Setup Commands
## Enable sharding for database
sh.enableSharding("myDatabase")
## Shard a specific collection
sh.shardCollection("myDatabase.myCollection", { userId: "hashed" })
5. Connection Pooling
// Node.js connection pooling example
const MongoClient = require('mongodb').MongoClient
const client = new MongoClient(url, {
poolSize: 10, // Optimal connection pool
useNewUrlParser: true
})
Tool |
Purpose |
Key Metrics |
mongostat |
Real-time server statistics |
Connections, operations |
mongotop |
Resource utilization |
Read/Write time |
Prometheus |
Advanced monitoring |
Comprehensive metrics |
7. Caching Strategies
## Enable in-memory storage engine
storage:
engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 2
Practical Considerations with LabEx
LabEx provides an excellent platform for practicing and understanding MongoDB optimization techniques in a controlled, interactive environment, allowing developers to experiment safely.