Backup and recovery are crucial aspects of MongoDB database administration. This guide covers various backup strategies, recovery procedures, and best practices to ensure data protection and business continuity.
MongoDB Backup & Recovery Strategies
# Full database backup
mongodump --db myDatabase --out /backup
# Specific collection backup
mongodump --db myDatabase --collection users --out /backup
# Compressed backup
mongodump --db myDatabase --gzip --out /backup
# Backup with authentication
mongodump --uri="mongodb://user:password@localhost:27017/myDatabase" --out /backup
# Restore entire database
mongorestore --db myDatabase /backup/myDatabase
# Restore specific collection
mongorestore --db myDatabase --collection users /backup/myDatabase/users.bson
# Restore compressed backup
mongorestore --gzip --db myDatabase /backup/myDatabase
# Restore with authentication
mongorestore --uri="mongodb://user:password@localhost:27017/myDatabase" /backup/myDatabase
Complete database backup including all collections and indexes
Backup of changes since the last backup
Real-time backup using oplog or replication
# Cron job for daily backup
0 2 * * * mongodump --db myDatabase --out /backup/$(date +\%Y\%m\%d)
# Backup script with rotation
#!/bin/bash
BACKUP_DIR="/backup"
RETENTION_DAYS=7
# Create backup
mongodump --db myDatabase --out $BACKUP_DIR/$(date +\%Y\%m\%d)
# Remove old backups
find $BACKUP_DIR -type d -mtime +$RETENTION_DAYS -exec rm -rf {} \;
Now that you understand MongoDB backup and recovery, you can explore: