Most MongoDB backup guides stop at the mongodump command line. That is the
easy part. What decides whether you get your data back is everything around it:
what the dump leaves out, which options change what you will be able to restore,
whether the script really fails when the dump fails, and whether anyone has ever
replayed the file.
This guide covers the whole chain. By the end you will know what a mongodump
holds and what it leaves to the server, when --oplog is worth anything, how to
write a backup script that cannot report success on an empty file, how to
restore the archive by hand in a throwaway container, and which questions asked
in mongosh tell you a restored database actually holds your data.
Everything here works with mongodump, docker and the AWS CLI, and nothing else.
What a mongodump backs up, and what it leaves out
mongodump reads documents over the server protocol, like any other client. So
it backs up data, not a server:
- users and roles are not part of it. They live in the
admindatabase, insystem.usersandsystem.roles; a dump limited to your business database does not hold them, and the restore then gives an intact database where no application account exists; - neither is the server configuration: the instance settings, the replica set membership, the sharding layout of a partitioned cluster;
- nor the other databases on the same server, unless you ask for a full dump.
Indexes, on the other hand, are in the dump — their definition, not their
content. mongorestore writes the documents first, then rebuilds each index. On
a large collection that is where most of the restore time goes, and it is the
reason a restore is almost always slower than the dump that produced it.
A dump is not a copy of the data directory
Both are defensible, but they do not give you the same thing.
A dump is logical: the documents are read back, reinserted, the indexes rebuilt.
It restores into another version of MongoDB, onto another machine, into a
different topology — a dump taken on a replica set reloads onto a standalone
server.
A copy of the data directory (--dbpath) is physical: these are the storage
engine's files. It restores much faster on large volumes, but it is only valid
for the same MongoDB version and the same storage engine, and it cannot be taken
by copying the files of a running server — you have to stop it, or go through a
filesystem snapshot that captures the journal along with the data.
For a database of a few gigabytes, mongodump stays the simple choice: one
file, readable by any recent MongoDB.
The options that decide what you will be able to restore
--archive writes everything into a single stream instead of a tree of BSON
files. That is one object to upload instead of a directory to synchronise, and
mongorestore reads it back as is.
--gzip compresses. With --archive, the compression happens in the stream: no
intermediate file, and mongorestore --gzip reads it back without decompressing
first.
--oplog changes the nature of the backup. Without it, a dump that takes
several minutes mixes documents read at different moments: an order can appear
without the billing line written in the same transaction. With it, mongodump
records the oplog position before starting, then appends the operations that
happened while reading, and mongorestore --oplogReplay replays them at the
end: the result is the state of the database at one point in time. Two
conditions: the oplog only exists on a replica set, and the option only applies
to a full dump of the instance, not to a --db.
Finally, the database name is inside the dump. mongodump records each
collection under its full namespace, shop.orders, and mongorestore
writes it back under that same name. Renaming the file changes nothing. That is
what makes the mistake in the restore section so easy to make.
The backup script
#!/bin/bash
set -euo pipefail
ts=$(date +%Y%m%d_%H%M%S)
dest=s3://backups-shop/mongo
mongodump --host mongo.internal --port 27017 --db shop --archive \
| gzip > "/backups/shop_${ts}.archive.gz"
aws s3 cp "/backups/shop_${ts}.archive.gz" "${dest}/"
Without
pipefail, a failed dump comes out as a successIn
mongodump | gzip, the shell only looks at the exit code of the last
link.gzipcompresses an empty stream very nicely, so the script returns 0
and cron is happy.set -o pipefail— included in theset -euo pipefail
above — makes the whole line fail as soon asmongodumpfails. The variant
without a pipe,--archive=/backups/... --gzip, removes the problem at the
source:mongodumpwrites the file itself and its exit code is the
command's.
Keep the timestamp in the file name: a file always overwritten under the same
name leaves no chance of going back to yesterday. For retention, a lifecycle
rule on the bucket deletes objects older than N days with no script to maintain.
The account taking the dump needs to read the whole database. A role that is too
narrow raises no visible error: it produces a dump where the collections it
cannot see are simply missing.
That leaves running it every night. A cron is enough, on two conditions: that
its error output goes somewhere someone reads, and that a run dragging on does
not overlap with the next one — flock -n on a lock file settles the second
point in one line.
Restoring once, by hand
A backup is only proven once restored. Do it once, in full, in a throwaway
container — it is also the procedure you will follow the day it matters.
docker run -d --name mongo-test mongo:7
until docker exec mongo-test mongosh --quiet --eval 'db.runCommand({ping:1})'; do sleep 1; done
docker cp /backups/shop_20260918_010000.archive.gz mongo-test:/tmp/dump.gz
docker exec mongo-test mongorestore --archive=/tmp/dump.gz --gzip --drop \
--nsInclude 'shop.*' --stopOnError
--drop removes each collection before rewriting it: without it, a restore into
a container already used mixes the documents of two attempts. --stopOnError
stops at the first refused insert, instead of carrying on and handing you a
half-restored database that looks like it works.
The database name is the dump's, not the one you want
If the archive was taken on a database named
store, the--nsIncludeabove matches nothing:
'shop.*'mongorestorerestores no document,
and exits with success. Nothing in the database warns you, because there is
no database. To restore under another name, you have to say so:
--nsFrom 'store.*' --nsTo 'shop.*'.
Use the same major version as your server instead of mongo:7 if it differs: a dump taken on a newer server does not necessarily replay on an older one.
Note how long it took. That is your real restore duration, the only one worth
comparing to the delay you promised.
What to check in a restored database
mongorestore finishing without an error does not mean the data is there. Four
questions, in this order, from a mongosh opened on the container:
use shop
show collections
db.orders.countDocuments()
db.orders.find().sort({ created_at: -1 }).limit(1)
db.orders.getIndexes().length
-
The collections are there. An empty list means an
--nsIncludethat recognised nothing, or an empty dump that replayed perfectly. -
The documents are there.
countDocuments()really counts, unlikeestimatedDocumentCount(), which reads the collection metadata and can report documents that are no longer there. Compare against the order of magnitude in production, not an exact number. - The data is recent. The most recent document should be yesterday's, not last month's. That is what catches a backup job that stopped running without saying anything.
- The indexes were rebuilt. A collection back with its documents but without its indexes behaves correctly and answers in seconds instead of milliseconds. On a production database put back in service, that is enough to make it unusable.
Then destroy everything: docker rm -f mongo-test.
What this chain does not prove
It proves that a recent archive restores into a fresh MongoDB and that the
collections come back with their documents. It does not prove that your
application works on that database: for that, start it against the restored database and run a few real requests. It says nothing about the users and roles left
in admin, which are not in a dump of a business database. It says nothing about how old the archive is: a March dump restores perfectly in September. And it says nothing
about what has been written since the last dump — that gap is your RPO, and it
is tuned with the backup frequency, not with the checks.
FAQ
What has to be backed up besides the business database?
Users and roles, which live in the admin database and are not in a dump
limited to your own. Without them, the restore gives you an intact database
where no application account exists and nobody can connect. The server
configuration and the replica set membership are not in the dump either, and
that is as it should be: they belong to the server.
Is --oplog useful on a standalone server?
No. The oplog only exists on a replica set. On a standalone instance the option
has nothing to record, and a dump that takes several minutes stays a mix of
documents read at different moments.
Should a mongodump archive be compressed?
Yes, with --gzip, which compresses inside the stream. A compressed archive
restores as is: mongorestore --archive=... --gzip reads it back without
decompressing first, so there is no intermediate file to plan for and no disk
space to reserve for it.
Why does a MongoDB restore fail without restoring anything?
Almost always because of a name. The database name is recorded inside the dump,
not in the file name: an --nsInclude matching no namespace in the archive
restores no document and exits with success. You have to read what the archive
holds before restoring it, or rename with --nsFrom and --nsTo.
Why is a restore slower than the dump that produced it?
Because of the indexes. The dump holds their definition, not their content:
mongorestore writes the documents first, then rebuilds each index, and on a
large collection that is where most of the time goes. It is also why you check
they came back: a collection returned without its indexes answers correctly, in
seconds instead of milliseconds.
Originally published on restoreproof.io.
RestoreProof runs this kind of restore test on a schedule, inside your own infrastructure, and signs a report proving the backup restores. Your data never leaves your servers. Free plan, no credit card: https://app.restoreproof.io
Top comments (2)
The line that stopped me was the quiet one: gzip compresses an empty stream very nicely, so the script returns 0 and cron is happy. That is the exact failure mode I worry about on the app side too — a backup that reports success is worse than no backup at all, because it kills the urgency to check. Your --nsInclude example is the same trap at the restore end: zero documents restored, exit code 0, nothing in the database to warn you. That is a terrifying kind of success.
The detail I will steal is the four mongosh checks in order, especially countDocuments() over estimatedDocumentCount(). Checking that the indexes actually came back is the one most guides skip, and it matters: a collection that answers correctly but in seconds instead of milliseconds is a production incident wearing a successful restore's clothes.
One question: you draw the line at proving the database restores, not that the app works on it — do you run the app against the throwaway container as a second step, or do you keep the restore test deliberately database-only so it stays fast enough to run on a schedule?
The independent counter is the part I would underline. Comparing a restore against yesterday's number from the same pipeline hides exactly the failure you are hunting: if the dump silently read half the collections, both numbers agree and the check passes. What I do instead is have a second read-only login count the same window straight from the source, so the restore is graded against a number it did not produce. The newest-document check you list does the same job differently, and I like that it needs no second system.
One question on --oplog: what happens when reading takes longer than the oplog window? On a busy instance that drift is minutes and the oplog rolls off underneath you. Does mongodump tell you it happened, or do you only find out when the replay is short? I have never been sure, so past a certain collection size I fall back to a filesystem snapshot and stop pretending the dump is point-in-time.