Skip to content
Navigation

Type at least two characters. Search covers page titles, headings, tags and database names.

↑ ↓ to navigateEnter to openEsc to close0 pages
MongoDBintermediate

MongoDB Backup and Restore

mongodump, filesystem snapshots and oplog-based point-in-time recovery, including what changes in a sharded cluster.

2 min readIntermediateUpdated Edit this page

mongodump

mongodump --uri="mongodb://backup@mongo-a.internal:27017/?replicaSet=shop-rs" \
  --readPreference=secondary \
  --oplog \
  --gzip --archive=/backups/shop-$(date -u +%Y%m%dT%H%M%SZ).archive.gz

--oplog captures oplog entries generated during the dump, so the restore is consistent to a single point rather than smeared across the dump's duration. It requires a replica set.

mongorestore --uri="mongodb://restore@mongo-verify.internal:27017" \
  --oplogReplay --gzip --archive=/backups/shop-20260731T020000Z.archive.gz

Filesystem snapshots

A volume snapshot of the data directory is fast and restores fast. It is only valid if the snapshot is atomic across all volumes holding the database, including the journal.

Requirements:

  • Journaling must be enabled — it is by default — and the journal must be on the snapshotted volume, or the snapshot is not recoverable.
  • If data and journal span several volumes, the snapshot must be coordinated across all of them, or use db.fsyncLock() to quiesce writes briefly.
db.fsyncLock();     // blocks writes — take the snapshot now
db.fsyncUnlock();

Point-in-time recovery

Restore the most recent full backup, then replay oplog entries up to the target moment:

# Dump the oplog range you need from a running member.
mongodump --uri="…" --db=local --collection=oplog.rs \
  --query='{"ts": {"$gte": {"$timestamp": {"t": 1753968000, "i": 1}}}}' \
  --out=/backups/oplog
 
mongorestore --uri="…" --oplogReplay --oplogLimit 1753970520:1 /backups/oplog

--oplogLimit stops replay at a timestamp, which is how you recover to just before a destructive operation. The oplog must still contain the range you need — see the oplog window discussion in Replica Sets.

Sharded clusters

Verification

// After restoring into a verification cluster.
db.getCollectionNames().forEach(c => print(c, db[c].countDocuments()));
db.orders.findOne({ _id: knownId });
db.runCommand({ dbStats: 1 });

Compare document counts per collection against the source, confirm indexes were rebuilt, and run one representative application query. Users and roles live in the admin database and must be included in the backup — a restore without them produces a database nobody can connect to.