Restore a MongoDB Backup from S3: Test Before Recovery
Restore a MongoDB backup from S3 into a scratch database with mongorestore. Check namespaces, inspect data, and rehearse recovery before touching production.
A backup you've never restored is not a backup. To restore a MongoDB backup from S3 safely, I start with a scratch database: download the archive, remap its namespaces with mongorestore, and inspect the result before considering a production cutover.
This continues the MongoDB backup-to-S3 guide and SES failure-alert setup. It assumes a single-database mongodump --archive --gzip backup, Database Tools compatible with your source and target, and permission to read the archive.
Run aws configure if the restore user has no credentials, or use an IAM role on EC2. This guide's interactive commands use aws; the later cron script uses the Snap invocation from the backup guide.
Restore permissions differ from backup permissions. The backup policy grants s3:PutObject and s3:ListBucket, not s3:GetObject. Grant object reads for the intended bucket or prefix, such as arn:aws:s3:::your-bucket-name/*. Check KMS decrypt permissions too if the objects use SSE-KMS. Do not grant broad S3 administrator access just to download one archive.
Check the download size. A truncated archive can produce Failed: archive parser: ... unexpected EOF. Compare the remote and local sizes:
aws s3 ls s3://your-bucket-name/backup-2026-08-24_02-00-00.gzls -l ~/restore/backup.gz
The byte counts should match. Matching sizes are a basic check, not proof of integrity or recoverability.
Restore to a disposable namespace first. This backup contains one database (mydatabase), so use --nsFrom and --nsTo to map it to mydatabase_restore. Confirm that the target namespace does not contain anything you need.
The restored collections now use mydatabase_restore, leaving the original namespace unchanged. A same-server restore still consumes CPU, memory, and disk I/O. Use a separate test server when production cannot absorb that load.
On an empty replacement server, you can omit namespace remapping. The command below includes --drop, which deletes target collections that are present in the archive before restoring them. Do not run it against live data without a recovery plan and stopped application writes.
Without --drop, a restore into populated collections can encounter duplicate keys. That is not a reason to add a destructive flag automatically. Inspect the target namespace first. Also, --drop does not remove target collections absent from the archive. See the official mongorestore options before choosing replacement behavior.
Compare the counts with a recorded baseline from the backup period where available. Current production may have changed since the dump. Then inspect a known document:
Counts and a sample document are initial checks, not a completeness guarantee. Check required indexes, important records, and application behavior against the restored database. Record failures before deleting the scratch data.
Only proceed after validation. Stop application writes and decide what happens to data created after the backup. Two approaches are possible:
Point the app at the restored database. Change the database name in the connection string and restart after checking permissions and configuration. This avoids copying the restored data again and leaves the original database available for investigation.
Move collections to the original namespace. The example below moves only orders, not an entire database:
Do not paste this as an unattended swap. The two commands are not atomic together, and the shown snippet does not stop on a failed command result. Stop the app and execute each operation separately, checking for { ok: 1 } before continuing.
Check rename support for your deployment and collection type first. A failed first rename must not be followed blindly by the second.
mongosh --quiet --eval ' db.getSiblingDB("admin").runCommand({ renameCollection: "mydatabase.orders", to: "mydatabase_old.orders", dropTarget: false }); db.getSiblingDB("admin").runCommand({ renameCollection: "mydatabase_restore.orders", to: "mydatabase.orders", dropTarget: false });'
Repeat the planned operations for each intended collection, with the appropriate privileges and deployment support. I generally prefer changing the app's database target. Even then, switching back after new writes is not a free rollback: account for those writes in the cutover plan.
A drill should make failures visible before an incident. This example downloads the latest archive by its date-stamped filename, restores it to a drill database, checks a known collection, and cleans up.
Read the cleanup behavior first. The script drops mydatabase_drill and deletes its downloaded archive on exit, including after failure. Reserve that namespace for disposable data. Change the expected orders collection to a collection you know should be nonempty. This is a smoke test, not an application-level recovery test.
nano ~/restore-drill.sh
#!/bin/bash# === Quarterly MongoDB restore drill ===# Same `snap run aws-cli.aws` approach as the backup post — see there for the cron/PATH rationale.set -eS3_BUCKET="s3://your-bucket-name"WORK_DIR="$HOME/restore-drill"DRILL_DB="mydatabase_drill"LOG_FILE="$HOME/restore-drill.log"# Always clean up the drill DB and local archive, even if a step failscleanup() { mongosh --quiet --eval "db.getSiblingDB('$DRILL_DB').dropDatabase();" 2>/dev/null || true rm -f "$WORK_DIR/drill.gz"}trap cleanup EXITmkdir -p "$WORK_DIR"echo "Starting restore drill: $(date)" >> "$LOG_FILE"# Grab the most recent archive by KEY name. `aws s3 ls` lines start with the# object's modification date, so sorting the raw output would let a re-uploaded# old archive masquerade as "latest". Pull out the key column ($4), keep only# backup archives, then sort by the date-stamped filename — and bail if none match.LATEST=$(snap run aws-cli.aws s3 ls "$S3_BUCKET/" \ | awk '{print $4}' \ | grep -E '^backup-.*\.gz$' \ | sort \ | tail -n 1)if [ -z "$LATEST" ]; then echo "No backup archives found in $S3_BUCKET — aborting drill." >> "$LOG_FILE" exit 1fiecho "Latest archive: $LATEST" >> "$LOG_FILE"snap run aws-cli.aws s3 cp "$S3_BUCKET/$LATEST" "$WORK_DIR/drill.gz" >> "$LOG_FILE" 2>&1# Restore into an isolated drill database, replacing any previous drill runmongorestore \ --uri="mongodb://localhost:27017" \ --gzip \ --archive="$WORK_DIR/drill.gz" \ --nsFrom="mydatabase.*" \ --nsTo="$DRILL_DB.*" \ --drop >> "$LOG_FILE" 2>&1# Prove it: print document counts per collectionmongosh --quiet --eval " const scratch = db.getSiblingDB('$DRILL_DB'); scratch.getCollectionNames().forEach(c => { print(c + ': ' + scratch.getCollection(c).countDocuments()); });" >> "$LOG_FILE" 2>&1# Assert a known collection actually came back — mongorestore can exit 0 with zero docsEXPECTED_COLLECTION="orders"COUNT=$(mongosh --quiet --eval "db.getSiblingDB('$DRILL_DB').getCollection('$EXPECTED_COLLECTION').countDocuments()")if ! [[ "$COUNT" =~ ^[0-9]+$ ]] || [ "$COUNT" -eq 0 ]; then echo "DRILL FAILED: $EXPECTED_COLLECTION is missing or empty (count=$COUNT)" >> "$LOG_FILE" exit 1fiecho "Drill verified: $EXPECTED_COLLECTION has $COUNT documents" >> "$LOG_FILE"# Drill DB and local archive are removed by the EXIT trap, on success or failureecho "Restore drill completed: $(date)" >> "$LOG_FILE"
Run it manually and inspect the log before scheduling it for the first day of each quarter:
The schedule runs at 03:00 in cron's configured time zone. The example does not include email handling. Add and test the SES failure-alert pattern separately if you need notifications. Check that the drill ran at all, not just whether it logged an error.
The archive may be truncated or corrupt. Download it again and compare sizes. If the error persists, check another archive and investigate the backup process.
A restored document conflicts with an existing unique key. Confirm the target namespace and inspect the data before choosing a fresh scratch target or intentional replacement.
Check mongorestore --version and compare the Database Tools release with the one that created the archive. Tools versions and server versions are separate. Review the documented source and target compatibility rather than assuming a newer binary can restore every older dump.
Check the URI, server availability, network access, TLS settings, and authentication. Use the appropriate authentication database for the target. Do not paste production credentials into shell history.
Original connection example:
Wrong --uri, MongoDB isn't running, or auth is required. Add credentials to the URI: mongodb://user:pass@localhost:27017/?authSource=admin.
No. mongorestore --gzip --archive=file.gz reads a compressed archive directly. If you already decompressed it, omit --gzip. Match the flags to the file format.
Yes. Point the URI at that server, then check authentication, network access, Tools compatibility, and target namespaces. An isolated server also avoids adding restore load to production.
Not for a separate scratch namespace, although a shared server can still suffer resource contention. For an in-place restore or cutover, stop application writes and plan how to handle data newer than the backup.
Measure the bottleneck before tuning insertion workers or index handling. Skipping index restoration changes what is ready at the end; rebuild and validate required indexes before serving traffic. There is no fixed speedup to promise.
No. It tests downloading an archive and restoring data into a database on an already configured server. Rebuilding hosts, users, credentials, network access, and application configuration needs a separate recovery rehearsal.