Continuous monitoring is essential for maintaining MongoDB performance, identifying bottlenecks, and ensuring system health in production environments.
// Database statistics
db.stats()
// Collection statistics
db.collection.stats()
// Current operations
db.currentOp()
// Replication status
rs.printSlaveReplicationInfo() // for older versions
rs.printSecondaryReplicationInfo() // for newer versions
// Server status
db.serverStatus()
Real-time monitoring tool:
# Basic monitoring
mongostat --host localhost:27017
# Detailed monitoring with intervals
mongostat --host localhost:27017 --rowcount 100
# Monitor specific collections
mongostat --host localhost:27017 --discover
Monitor read/write activity per collection:
# Monitor top activity
mongotop --host localhost:27017 2
# Monitor MongoDB process
top -p $(pgrep mongod)
# Check disk usage
df -h /var/lib/mongo
iostat -x 1
# Network monitoring
iftop -i eth0
Configure MongoDB Exporter:
# docker-compose.yml
version: '3'
services:
mongodb-exporter:
image: percona/mongodb_exporter:0.36
environment:
- MONGODB_URI=mongodb://username:password@mongodb:27017
ports:
- "9216:9216"
Many cloud providers offer MongoDB monitoring integrations.
Enable and monitor MongoDB logs:
# In mongod.conf
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
verbosity: 1 # Increase for debugging
component:
storage:
verbosity: 0
index:
verbosity: 0
replication:
verbosity: 1
sharding:
verbosity: 0
Monitor for:
#!/bin/bash
# MongoDB health check script
MONGO_STATUS=$(mongosh --eval "db.adminCommand('ping')" --quiet 2>/dev/null | grep -o "ok.*: 1" | wc -l)
if [ "$MONGO_STATUS" -eq 1 ]; then
echo "MongoDB is healthy"
exit 0
else
echo "MongoDB is not responding"
exit 1
fi
#!/bin/bash
# MongoDB resource monitoring
# Check disk space
DISK_USAGE=$(df /var/lib/mongo | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 85 ]; then
echo "WARNING: Disk usage is ${DISK_USAGE}%"
fi
# Check memory usage
MEM_USAGE=$(ps aux | grep mongod | grep -v grep | awk '{print $4}')
if (( $(echo "$MEM_USAGE > 80" | bc -l) )); then
echo "WARNING: Memory usage is ${MEM_USAGE}%"
fi