MongoDB Backup and Restore: mongodump, mongorestore, and What to Test
Back up MongoDB with mongodump, snapshots or managed backup, restore with mongorestore and oplog replay, and test restores before you need them.
MongoDB backup and restore is the part of operations that everyone agrees is important and few teams rehearse. A backup job that reports success every night proves only that files were written. It says nothing about whether you can get a working database back, how long that takes, or whether the data is complete. Here I write about the backup methods MongoDB supports, the commands and flags I use. I also cover the restore testing that turns backups into something you can rely on.
Replication does not replace any of this. As I explain in the replica sets post, a replica set copies mistakes as faithfully as it copies good writes.
MongoDB Backup Options Compared
There are three broad approaches. Which fits depends on two numbers you should agree with the business first. One is the recovery point objective (RPO), how much recent data you can afford to lose, and the recovery time objective (RTO), how long you can be down while restoring.
| Method | Typical RPO | Restore speed | Works for sharded clusters | Notes |
|---|---|---|---|---|
| mongodump / mongorestore | Time since last dump, or less with oplog | Slow on large data, indexes rebuild | Not for consistent backups with sharded transactions | Simple, logical, portable between versions |
| Filesystem or volume snapshots | Time since last snapshot | Fast, copy files back | Yes, with coordination | Needs consistent snapshot of data and journal |
| Atlas, Ops Manager or Cloud Manager backup | Seconds to minutes with continuous backup | Fast, point in time | Yes | Managed, costs money, least operational work |
mongodump is a logical backup: it reads documents and writes BSON. Snapshots are physical backups of the data files. Managed services combine snapshots with oplog capture so you can restore to a chosen moment. Many production setups use two of these at once. They pair managed or snapshot backups for fast full recovery, plus a periodic logical dump that can be restored into a different MongoDB version or inspected collection by collection without restoring everything.
mongodump Basics
mongodump and mongorestore ship with the server, in the mongodb-org-tools package on Linux, and carry the same version number as the server. I use the tools from the same release series as the cluster I am backing up. So a 4.2 cluster gets 4.2 tools. A typical full dump of a replica set:
mongodump \
--uri="mongodb://backup-user@db-b.internal:27017,db-c.internal:27017/?replicaSet=rs0&authSource=admin" \
--readPreference=secondary \
--oplog \
--gzip \
--archive=/backups/shop-$(date +%F).archive.gz
--oplog is the flag people skip and should not. A dump of a busy database takes time, and documents change while it runs. As a result, collections dumped at the start and the end reflect different moments. --oplog captures the oplog entries written during the dump so that a restore with --oplogReplay brings everything to a single consistent point at the end of the dump. It works against a replica set member, not a mongos. --readPreference=secondary keeps the dump’s reads off the primary. --gzip with --archive writes one compressed file. That is easier to ship, encrypt and checksum than a directory of BSON files.
You can narrow a dump with --db, --collection or --query, though --oplog only applies to full-instance dumps. The user running the dump needs the backup role and nothing more, as I describe in the security best practices post. The mongodump reference lists every option.
MongoDB Restore With mongorestore
A full restore of that archive with the captured oplog:
mongorestore \
--uri="mongodb://restore-user@restore-host:27017/?authSource=admin" \
--gzip \
--archive=/backups/shop-2020-01-27.archive.gz \
--oplogReplay \
--drop
--drop drops each collection before restoring it, so the result matches the backup rather than merging into existing data. To restore one collection, or restore under a different name for inspection, use namespace filters:
mongorestore --gzip --archive=/backups/shop-2020-01-27.archive.gz \
--nsInclude='shop.orders' --nsFrom='shop.*' --nsTo='shop_check.*'
When I tested this with the 4.2 tools, mongorestore refused to combine --oplogReplay with a namespace rename, reporting that it cannot use --oplogReplay with namespace renames specified, and it refuses --nsInclude with --oplogReplay in the same way. So a renamed restore is consistent per collection, but not across collections at a single point. That is fine for pulling back a few deleted documents and not fine for a full recovery. --dryRun shows what would be restored without writing anything.
Restore speed is where expectations break. mongorestore inserts every document and then builds every index, and index builds on large collections can take longer than loading the data. --numParallelCollections (default 4) and --numInsertionWorkersPerCollection add parallelism if the target has spare CPU and disk. --noIndexRestore loads data without indexes, which only helps if you plan to build them yourself later. The mongorestore reference covers the rest.
Snapshots
Filesystem or cloud volume snapshots, such as LVM or EBS, copy data files almost instantly and restore far faster than mongorestore, because no documents are reinserted and no indexes rebuilt. The requirement is consistency. If the data files and the journal are on the same volume, a snapshot of that volume is consistent. On restart MongoDB recovers from its last checkpoint plus the journal. If they are on different volumes, or you snapshot several volumes, lock writes first:
db.fsyncLock()
// take the snapshot of every volume here
db.fsyncUnlock()
Run the lock on a secondary so the primary keeps serving writes, keep the locked window short. Always release the lock in a finally-style step of your script so a failed snapshot does not leave the member locked. The backup methods overview compares these approaches in detail.
MongoDB Backup and Restore for Sharded Clusters
Sharded clusters are where homemade backups get hard. A consistent backup must capture every shard and the config server replica set at the same logical moment. Meanwhile, the balancer could be moving data between them. MongoDB 4.2 added transactions across shards, and with them a hard rule: mongodump and mongorestore cannot be part of a backup strategy for a 4.2 sharded cluster that has sharded transactions in progress, because a dump of each shard cannot capture a transaction that spans several of them atomically.
The approaches that work are managed backups, which coordinate this for you, or coordinated snapshots. With snapshots you stop the balancer, snapshot the config servers and one member of each shard, then restart the balancer.
sh.stopBalancer()
sh.getBalancerState() // false
sh.isBalancerRunning() // wait until this is false too
// snapshot config server and one member per shard
sh.startBalancer()
sh.stopBalancer() waits for the current migration round, but I still check sh.isBalancerRunning() before taking snapshots. The sharded cluster snapshot tutorial gives the full order of steps. Restoring a sharded cluster from snapshots is a multi-step procedure with config metadata to fix up. So rehearse it before you need it. My sharding post covers why I prefer managed backups once a cluster is sharded.
Point in Time Recovery
Most real restores are not about a dead server. They are about a bad deploy or an accidental deleteMany at a known time. In that case you want the database as it was just before. With logical tools, that means restoring the last good dump and replaying oplog entries up to the moment before the mistake:
# Dump the oplog from a member whose window still covers the incident
mongodump --uri="mongodb://backup-user@db-b.internal:27017/?authSource=admin" \
-d local -c oplog.rs --out=/restore/oplog
# Restore the last full dump, then replay up to just before the bad operation
mongorestore --uri="mongodb://restore-host:27017" --gzip --archive=/backups/shop-2020-01-27.archive.gz --oplogReplay --drop
mongorestore --uri="mongodb://restore-host:27017" --oplogReplay \
--oplogFile=/restore/oplog/local/oplog.rs.bson --oplogLimit=1580115600:1 /restore/empty-dir
--oplogLimit takes a timestamp in seconds with an optional ordinal and replays only entries before it. Find the timestamp of the bad operation by querying local.oplog.rs for it, for example:
db.getSiblingDB("local").oplog.rs.find({ ns: "shop.orders", op: "d" }).sort({ $natural: -1 }).limit(1)
The ts field of the result is the timestamp to pass, and an accidental deleteMany shows up as a run of delete entries with op: "d". The target directory in the replay command can be empty, because the oplog file supplies everything. This only works while the oplog window still covers the period between the last dump and the incident. That is another reason to size the oplog generously. Managed continuous backups do the same thing through a UI, which is a big part of what you pay for.
What to Test in a MongoDB Backup and Restore
A restore drill answers three questions: does it work, how long does it take, and is the data right. I run one on a schedule, at least quarterly, on a separate host:
- Restore the latest backup using only the written runbook, timing each step.
- Compare document counts and spot-check content against production.
- Point a staging copy of the application at the restored data and run a smoke test.
- Record the total time against the RTO and fix whatever was slow or unclear.
A simple validation script compares counts collection by collection:
const source = db.getSiblingDB("shop")
const restored = db.getSiblingDB("shop_restore")
source.getCollectionNames().forEach(name => {
const a = source.getCollection(name).estimatedDocumentCount()
const b = restored.getCollection(name).estimatedDocumentCount()
print(`${name}: source=${a} restored=${b} ${a === b ? "OK" : "DIFF"}`)
})
Counts on a live source will drift by whatever was written since the backup. So I look for large differences and missing collections rather than exact matches. Backup files need the same protection as the database: encrypted at rest, stored away from the primary’s disks and region, and readable only by the backup and restore roles.
Worked Example: Why Restores Take Longer Than Dumps
A pattern I have watched teams discover the hard way. The nightly dump finishes in a comfortable window, so everyone assumes a restore takes about as long. Then the first real restore runs far longer. The dump only read documents, while the restore must insert them and then rebuild every index from scratch. Collections with many indexes, especially large compound or text indexes, spend most of the restore in index builds.
The fixes are straightforward once you see them. Measure the restore in a drill rather than estimating it from dump time. Drop indexes nobody uses before they cost you restore time. Give the restore host more CPU and faster disks than production, since it only exists for the restore. And if the measured restore time does not fit the RTO, move that system to snapshots or a managed backup, which restore files instead of rebuilding them.
Decision Framework: Picking a MongoDB Backup Strategy
For small replica sets, up to tens of gigabytes, nightly mongodump --oplog to encrypted off-site storage is usually enough, as long as restores are tested. As data grows, restore time is what pushes you to snapshots. For sharded clusters or tight RPO and RTO targets, managed backups with continuous point in time recovery earn their cost. Budget matters, but compare it with the cost of a day of downtime, not with zero.
Common MongoDB Backup and Restore Mistakes
The mistake I have seen most is backups that have never been restored, discovered to be incomplete during an incident. Close behind: dumping from the primary at peak load, dumping without --oplog so the backup is internally inconsistent, and keeping backups on the same disk or in the same account as the database they protect.
Frequently Asked Questions
Is mongodump enough for production?
For small replica sets with modest RTO targets, yes, if you use --oplog, store archives off-site and test restores. For large datasets or sharded clusters, restore time and consistency limits push you to snapshots or managed backups.
How long will a restore take?
Longer than the dump, because restore rebuilds indexes. The only reliable answer for MongoDB backup and restore timing is to run a full restore drill on hardware like the hardware you would use in an incident.
Can I back up a single collection?
Yes, mongodump --db shop --collection orders does it, and --nsInclude restores a single collection from a full dump. You lose --oplog consistency for a single-collection dump, which is usually acceptable.
Are replica sets a backup?
No. They protect against hardware failure, not against bad writes, which replicate to every member within seconds. You need backups that sit outside the replica set and go back in time.
Schedule a restore drill this month. Restore your latest backup to a fresh host using only your written runbook, and time it end to end. Then compare the result with the recovery time you have promised. The gap between those two numbers is your most important backup task, and closing it is what makes MongoDB backup and restore something you can trust.
Last updated on 26 October 2026