Effective backup and recovery strategies are critical for maintaining data integrity and ensuring business continuity in MongoDB deployments.
The most common approach for logical backups:
# Create a backup
mongodump --uri="mongodb://username:password@localhost:27017" --out=/backup/mongodb/$(date +%Y%m%d_%H%M%S)
# Restore from backup
mongorestore --uri="mongodb://username:password@localhost:27017" /backup/mongodb/backup_date
For WiredTiger storage engine, you can use file system snapshots:
# Flush writes to disk and lock database
mongo admin --eval "db.fsyncLock()"
# Take filesystem snapshot here
# ... your snapshot command ...
# Unlock database
mongo admin --eval "db.fsyncUnlock()"
Using oplog for point-in-time recovery:
# Tail the oplog for continuous backup
mongodump --oplog --uri="mongodb://username:password@localhost:27017" --out=/backup/oplog_backup
Example cron job for daily backups:
#!/bin/bash
BACKUP_DIR="/backup/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
MONGO_HOST="localhost"
MONGO_PORT="27017"
mkdir -p $BACKUP_DIR/$DATE
mongodump --host $MONGO_HOST:$MONGO_PORT --out=$BACKUP_DIR/$DATE --gzip
# Remove backups older than 7 days
find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} +
Add to crontab for daily execution:
0 2 * * * /path/to/backup_script.sh
# Stop application connections
# Restore data
mongorestore --drop --uri="mongodb://username:password@localhost:27017" /path/to/backup/
# Restart services
# Restore from base backup first
mongorestore --oplogReplay --oplogLimit <timestamp> /path/to/backup/
Always validate backup integrity:
# Check backup structure
ls -la /path/to/backup/
# Verify data count matches production