MongoDB Backup, Restore & Migration Guide
In this article
This guide walks you through safely backing up, restoring, and migrating a MongoDB database, whether you're moving to a new server, upgrading hardware, or just creating a disaster recovery copy. You’ll learn both the standard command-line tools and best practices to avoid data loss or corruption.
What You'll Need
- Access to the MongoDB server (shell or SSH) with sufficient privileges (usually the
rootor a user withbackup/restoreroles). - MongoDB Database Tools installed on the machine where you run the commands (
mongodump,mongorestore,mongoexport,mongoimport). These are separate from the MongoDB server package – download them from the official MongoDB site if needed. - Enough disk space on the target location to hold the dump (usually less than the raw data size, but plan for at least the size of your largest collection).
- For migrations: network access between the source and destination servers, or a way to transfer the dump file (SCP, rsync, USB drive).
Step-by-Step
1. Prepare for Backup
Before dumping, ensure your MongoDB instance is running and healthy. If you’re using replica sets or sharded clusters, consider using mongodump with the --oplog option to capture a point-in-time consistent snapshot. For standalone instances, you can simply stop writes or accept a minor inconsistency window.
2. Create a Backup with mongodump
The basic command to back up a single database:
mongodump --db myDatabase --out /path/to/backup/
To back up all databases:
mongodump --out /path/to/backup/
For a replica set, add --oplog to capture ongoing operations during the dump:
mongodump --oplog --out /path/to/backup/
If your MongoDB requires authentication, include --username, --password, and --authenticationDatabase (usually admin).
3. Verify the Backup
After the dump completes, check the output directory. You should see a folder per database, containing .bson files (binary JSON) and .metadata.json files. Verify the file sizes are non-zero and the timestamps are recent. Optionally, restore to a temporary instance to confirm integrity.
4. Restore from Backup
To restore a single database from a dump:
mongorestore --db myDatabase --drop /path/to/backup/myDatabase/
The --drop flag drops the existing collection before restoring, avoiding duplicate key errors. For all databases, omit --db:
mongorestore /path/to/backup/
If you used --oplog during backup, you must replay the oplog during restore to get a consistent snapshot. Use --oplogReplay:
mongorestore --oplogReplay /path/to/backup/
5. Migrate to a New Server
Migration is essentially backup + restore on a different machine. Steps:
- Create a backup using
mongodumpas above. - Transfer the dump folder to the new server using
scp,rsync, or a shared drive. - On the new server, ensure MongoDB is installed and running.
- Restore using
mongorestoreas above. - Update your application connection strings to point to the new server.
For live migrations with minimal downtime, consider using mongomirror (for Atlas) or setting up a replica set with the new server as a member, then promoting it.
6. Alternative: Export/Import for Specific Collections
If you only need a few collections, use mongoexport to export to JSON/CSV and mongoimport to import:
mongoexport --db myDatabase --collection users --out users.json
mongoimport --db myDatabase --collection users --file users.json
Note: this does not preserve indexes or BSON data types perfectly – prefer mongodump for full fidelity.
Common Mistakes
- Not using
--oplogon a replica set, leading to an inconsistent backup. - Restoring without
--drop, causing duplicate key errors if the collection already exists. - Running
mongodumpwhile the server is under heavy write load – this can lead to a snapshot that is not transactionally consistent (unless using--oplog). - Forgetting to include authentication credentials, resulting in “command not allowed” errors.
- Transferring the dump folder without compression, wasting time and bandwidth.
- Restoring to a different MongoDB version – dump files may not be compatible across major versions.
Tips
- Compress the dump to save space:
mongodump --gzip --archive=/path/to/backup.gz. Restore withmongorestore --gzip --archive=/path/to/backup.gz. - Schedule regular backups using cron or a job scheduler, and test restores periodically.
- Use
--excludeCollectionto skip large, non-critical collections if you need a faster backup. - For sharded clusters, use
mongodumpon themongosinstance with--oplogto get a consistent view. - Keep a copy of the dump offsite (cloud storage, different data center) for disaster recovery.
Troubleshooting
Connection refused: Ensure MongoDB is running (sudo systemctl status mongod) and listening on the expected port (default 27017). If remote, check firewall rules.
Authentication failed: Verify your username, password, and authentication database. You may need to create a user with backup and restore roles.
“Failed: error connecting to db server”: Check that the host and port are correct, and that you’re using the right protocol (mongodb:// vs mongodb+srv://).
Restore fails with “Cannot insert multiple documents” or “E11000 duplicate key”: Use the --drop flag or manually drop the collection before restore.
Oplog replay error: If you used --oplog but didn’t replay it, you may have an inconsistent snapshot. Restore again with --oplogReplay.
Disk full during dump: Check available space with df -h. Use --gzip to reduce size, or dump to a different location.
Version mismatch: If you’re migrating to a different MongoDB version, check compatibility. You may need to upgrade/downgrade the dump format using mongodump and mongorestore from the same version as the target.
Frequently Asked Questions
Can I back up a live MongoDB database without stopping it?
Yes, mongodump is designed for hot backups. For replica sets, use --oplog to ensure consistency. For standalone instances, the backup may not be perfectly point-in-time consistent, but it’s usually fine for most use cases.
What’s the difference between mongodump and mongoexport?
mongodump creates a binary BSON dump that preserves all data types and indexes (in metadata files). mongoexport exports to human-readable JSON/CSV, but loses some type fidelity and index definitions. For full backups, always use mongodump.
How do I restore only a single collection from a full dump?
Use mongorestore --db yourDatabase --collection yourCollection /path/to/dump/yourDatabase/yourCollection.bson. You can also specify the namespace with --nsInclude.
Can I migrate a MongoDB database from a local server to MongoDB Atlas?
Yes, you can use mongodump to create a backup, then use mongorestore to upload it to Atlas. Alternatively, Atlas provides a live migration tool (mongomirror) for minimal downtime.
Is it safe to copy the data files directly (e.g., /var/lib/mongodb)?
Not recommended. MongoDB uses journaling and internal locks; copying files while the server is running can lead to corruption. If you must, shut down the server cleanly, copy the files, and restart. But using mongodump is the safest and most portable method.
How long does a backup take?
It depends on the data size, server load, and disk speed. For a rough estimate, time a test backup of a subset. In general, mongodump is I/O intensive but can run in parallel with normal operations.