Preparation Before Recovery
Before starting data recovery on Ubuntu, two critical steps ensure a smooth process:
sudo systemctl stop mongod
to stop the service.mongodump
) are complete and not corrupted. For compressed backups (.gz
), check the file size and checksum (if available) to avoid restoring damaged data.Basic Recovery with mongorestore
The most common method for recovering MongoDB data is using the mongorestore
command. Follow these steps:
mongorestore
is available. Run sudo apt update && sudo apt install -y mongodb-org-tools
to install it.mongorestore --db <database_name> <backup_directory>
Replace <database_name>
with the target database (e.g., mydb
) and <backup_directory>
with the path to your backup (e.g., /backup/mydb
).--drop
: Deletes the existing database before restoring (use with caution to avoid accidental data loss).--gzip
: Handles compressed backup files (e.g., mongorestore --gzip /backup/mydb.gz
).sudo systemctl start mongod
.Point-in-Time Recovery with Oplog
For precise recovery (e.g., after a mistaken deletion), use the oplog (operation log)—a capped collection that records all write operations in a replica set. Here’s how:
/var/lib/mongodb/local/oplog.rs
) to a safe location.mongorestore
with --oplogReplay
to replay operations up to a specific timestamp:mongorestore --oplogReplay --db <database_name> --nsInclude '<collection_name>' <oplog_backup_directory>
<collection_name>
with the affected collection and <oplog_backup_directory>
with the path to the copied oplog file. This restores all operations (inserts, updates, deletes) performed before the specified time.Handling Different Backup Scenarios
mongodump
) restore the entire database.mongorestore --oplogReplay
to apply incremental changes after a full restore..tar.gz
or .gz
), decompress them first (gunzip /path/to/backup.gz
) or use mongorestore --gzip
to handle compression directly.Post-Recovery Verification
After recovery, validate data integrity to ensure success:
mongo
to open the shell.use mydb; db.mycollection.find().pretty();
/var/log/mongodb/mongod.log
) for errors or warnings during recovery.Alternative Recovery Methods
mongodump
) and should be a last resort.Best Practices for Future Prevention
cron
(e.g., daily mongodump
at midnight). Example cron job:0 0 * * * /usr/bin/mongodump --out /path/to/backup/$(date +\%Y\%m\%d)