SN

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.

9 min readUpdated October 26, 2026

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.

Key takeaways

  • Pick an archive from before the incident, not simply the newest object.
  • Restore to a separate namespace and inspect known collections and records.
  • Treat production cutover as a separate, planned operation.
  • Rehearse the download and restore on a schedule. A successful command alone is not a recovery test.

Restore a MongoDB backup from S3: the workflow

AWS S3 (backup-YYYY-MM-DD.gz)
   ↓  aws s3 cp
Local archive
   ↓  mongorestore --gzip --archive
Scratch database (mydatabase_restore)
   ↓  verify counts + sample docs
Promote to production (or drop it)

1. Find the archive you want in S3

List the bucket contents before choosing an archive:

aws s3 ls s3://your-bucket-name/ --human-readable

The output will resemble these example archives:

2026-08-22 02:00:11    1.9 GiB backup-2026-08-22_02-00-00.gz
2026-08-23 02:00:09    1.9 GiB backup-2026-08-23_02-00-00.gz
2026-08-24 02:00:12    1.9 GiB backup-2026-08-24_02-00-00.gz

Pick a backup that predates the incident. The newest archive may already contain the unwanted changes.

2. Download it to the server

mkdir -p ~/restore/
aws s3 cp s3://your-bucket-name/backup-2026-08-24_02-00-00.gz ~/restore/backup.gz

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.gz
ls -l ~/restore/backup.gz

The byte counts should match. Matching sizes are a basic check, not proof of integrity or recoverability.

3. Restore into a scratch database first

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.

mongorestore \
  --uri="mongodb://localhost:27017" \
  --gzip \
  --archive=$HOME/restore/backup.gz \
  --nsFrom="mydatabase.*" \
  --nsTo="mydatabase_restore.*"

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.

Restore to the original namespace only when intended

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.

mongorestore \
  --uri="mongodb://localhost:27017" \
  --gzip \
  --archive=$HOME/restore/backup.gz \
  --drop

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.

4. Restore just one collection

If you only need one collection, limit the source with --nsInclude and keep the scratch mapping:

mongorestore \
  --uri="mongodb://localhost:27017" \
  --gzip \
  --archive=$HOME/restore/backup.gz \
  --nsInclude="mydatabase.orders" \
  --nsFrom="mydatabase.*" \
  --nsTo="mydatabase_restore.*"

This selects orders for the scratch restore. Inspect the recovered documents before deciding how to copy any data back.

5. Verify the restored data

A successful command is not enough. A namespace filter can match no documents without proving useful recovery. Start by listing collection counts:

mongosh --quiet --eval '
  const scratch = db.getSiblingDB("mydatabase_restore");
  scratch.getCollectionNames().forEach(c => {
    print(c + ": " + scratch.getCollection(c).countDocuments());
  });
'

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:

mongosh --quiet --eval '
  printjson(db.getSiblingDB("mydatabase_restore").orders.findOne());
'

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.

6. Plan the production cutover

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.

7. Automate a quarterly restore drill

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 -e
 
S3_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 fails
cleanup() {
  mongosh --quiet --eval "db.getSiblingDB('$DRILL_DB').dropDatabase();" 2>/dev/null || true
  rm -f "$WORK_DIR/drill.gz"
}
trap cleanup EXIT
 
mkdir -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 1
fi
 
echo "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 run
mongorestore \
  --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 collection
mongosh --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 docs
EXPECTED_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 1
fi
echo "Drill verified: $EXPECTED_COLLECTION has $COUNT documents" >> "$LOG_FILE"
 
# Drill DB and local archive are removed by the EXIT trap, on success or failure
echo "Restore drill completed: $(date)" >> "$LOG_FILE"

Run it manually and inspect the log before scheduling it for the first day of each quarter:

chmod +x ~/restore-drill.sh
~/restore-drill.sh
0 3 1 1,4,7,10 * $HOME/restore-drill.sh >> $HOME/restore-drill.log 2>&1

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.

Troubleshoot restore errors

Failed: archive parser: ... unexpected EOF

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.

E11000 duplicate key error collection: mydatabase.orders index: _id_

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.

Failed: ... requires mongorestore version >= X

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.

Failed: error connecting to db server: no reachable servers

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.

FAQ

Do I need to decompress the archive first?

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.

Can I restore to a staging server?

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.

Must I stop the application?

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.

How can I make a slow restore faster?

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.

Does the quarterly script test a complete server rebuild?

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.

Complete the backup and recovery loop

  1. Automate MongoDB backups to S3 to create and store the archive.
  2. Add SES failure alerts for failed dump and upload commands.
  3. Restore to a scratch target, validate the application data, and record the result.

Run the drill before an incident makes the schedule for you.