DEV3 Technologies home

DEV3 Developer Forum

How do I back up and restore MongoDB with mongodump and mongorestore?

DevOps helpSolved0 views
dev3 ·

I run a single MongoDB instance for a Node app and have no backups. What is the simplest reliable way to dump and restore a database, and what about replica sets?

#mongodb#backup#mongodump

0

1 reply

dev3 · Accepted answer

mongodump and mongorestore (MongoDB Database Tools, installed separately from the server in recent versions) are the simplest logical backup.

Dump one database, compressed, into a single archive

mongodump --uri="mongodb://backup:PASS@127.0.0.1:27017/app?authSource=admin" \
  --archive=/var/backups/mongo/app-$(date +%F).gz --gzip

Restore

mongorestore --uri="mongodb://admin:PASS@127.0.0.1:27017/?authSource=admin" \
  --archive=/var/backups/mongo/app-2026-11-09.gz --gzip --drop

--drop removes existing collections first so the restore matches the backup. To restore into a different database name use --nsFrom='app.*' --nsTo='app_copy.*'.

Consistency on replica sets. Add --oplog to a full-instance dump (not with --db) to capture writes made during the dump, and --oplogReplay on restore, so you get a point-in-time consistent result.

Backup user. Use the built-in backup role (and restore for restores) instead of root.

Automate with cron, rotate with find ... -mtime +14 -delete, and copy offsite just as with MySQL. Keep secrets out of the command line with a config file via --config (YAML with uri: ...).

Larger deployments

  • Filesystem or LVM snapshots, or cloud snapshots, are faster for big data. For WiredTiger use journaling and snapshot the whole data directory.
  • Managed Atlas clusters provide continuous cloud backups.

Pitfalls

  • Copying /var/lib/mongodb while the server runs gives a corrupt backup.
  • Indexes are rebuilt on restore, so time is dominated by index building.
  • Test restores on a scratch instance, and check the document counts.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.