MongoDB's default configuration works for development, but production workloads benefit from monitoring key metrics and tuning specific settings. This guide covers the essentials.
Checking Current Server Status
mongosh
db.serverStatus()
Monitoring Connections
db.serverStatus().connections
Watch for connections approaching your configured limit, which can indicate the application isn't closing connections properly or genuinely needs a higher limit.
Enabling the Database Profiler
db.setProfilingLevel(1, { slowms: 100 })
This logs any operation taking longer than 100ms. Review captured slow operations:
db.system.profile.find().sort({ millis: -1 }).limit(10)
Using explain() to Analyze Query Performance
db.orders.find({ customerId: 123 }).explain("executionStats")
Look at totalDocsExamined versus nReturned — a large gap indicates the query is scanning far more documents than it's actually returning, usually meaning a missing index.
Creating Indexes
db.orders.createIndex({ customerId: 1 })
Listing Existing Indexes
db.orders.getIndexes()
Checking Index Usage
db.orders.aggregate([{ $indexStats: {} }])
Identifies indexes that are rarely or never used — unused indexes still cost write performance and storage, so removing them can help.
Monitoring Memory Usage (WiredTiger Cache)
db.serverStatus().wiredTiger.cache
By default, MongoDB's WiredTiger storage engine uses 50% of available RAM (minus 1GB) for its cache — adjust if running alongside other memory-intensive services on the same VPS:
sudo nano /etc/mongod.conf
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 2
sudo systemctl restart mongod
Checking Replication Lag (If Using a Replica Set)
rs.printSecondaryReplicationInfo()
Common Performance Issues
| Symptom | Likely Cause |
|---|---|
| Slow queries despite low server load | Missing index |
| High memory usage | WiredTiger cache sized too large relative to available RAM |
| Slow writes | Too many indexes on a frequently-written collection |
| Connection errors under load | Connection pool limit reached |
Using MongoDB Compass for Visual Monitoring
MongoDB Compass (the official GUI) includes a performance tab showing real-time operation counts and query performance visually, useful as a complement to command-line profiling.
Common Errors
"too many open connections" — review application connection pooling configuration; connections should be reused, not opened fresh for every operation.
Best Practices
- Create indexes matching your actual query patterns, verified with
explain() - Monitor and remove genuinely unused indexes periodically
- Size the WiredTiger cache appropriately for your VPS's total available RAM
Related Articles
- How to Install MongoDB on Ubuntu & Debian
- How to Check VPS Resource Usage (CPU, RAM & Disk)
- Database Security Checklist: Protecting MySQL, PostgreSQL & MongoDB
