Skip to content

MongoDB backups with mongodump and mongorestore

Logical backups for MongoDB with mongodump, parallel collection dumps, point-in-time strategies with oplog replay, and the restore drill that proves the dump works.

mongodump produces a BSON snapshot of a MongoDB database — one directory per database, one BSON file per collection, plus an optional oplog tail for near-PITR. It is the right tool for databases under roughly 100 GB and for cross-version restores. This article covers the dump invocation that captures a consistent snapshot from a replica set, the oplog tail that gives you point-in-time recovery, and the restore drill that proves the file works.

How to verify

To check the contents of a dump directory without restoring:

# Directory layout
ls -lh /var/backups/mongodb/dump-$(date +%F)/
# Expected:
# orders/    reports/    admin/
# Each subdirectory contains <collection>.bson and <collection>.metadata.json

# Inspect a single collection
bsondump --quiet /var/backups/mongodb/dump-$(date +%F)/orders/orders.bson | head -3

# Restore into a sandbox container and verify
docker run --rm -d -p 27018:27017 --name mongo-test mongo:7
mongorestore --uri="mongodb://127.0.0.1:27018" \
  --dir=/var/backups/mongodb/dump-$(date +%F)/
mongosh "mongodb://127.0.0.1:27018/orders" --eval "db.orders.countDocuments()"
docker stop mongo-test

What’s happening

mongodump connects as a regular client, runs db.collection.find() against each collection, and writes the BSON to disk. By default it does not lock — you get an inconsistent snapshot of any data changing during the dump. For a consistent backup of a replica set, dump from a secondary (lower load on primary) and use --oplog to capture the oplog tail; mongorestore --oplogReplay then replays the tail to bring the restore to the exact point the dump ended.

For a single mongod (no replica set), --oplog is unavailable — you get only the in-flight snapshot. For point-in-time recovery you must run as a replica set even if it is a single-node one. This is one reason to always deploy MongoDB as a replica set, even in development.

Output formats: by default mongodump writes a directory tree (one directory per database). With --archive, it writes a single archive file you can stream to stdout. With --gzip, the BSON files are gzipped. The standard production pattern is --archive --gzip to one file, easy to ship.

The procedure

  1. Create a backup user with the minimum required role.

    use admin
    db.createUser({
      user: "backup",
      pwd: "strong-password",
      roles: [{ role: "backup", db: "admin" }]
    })

    The backup role is the built-in role with read access to all databases plus the necessary oplog access.

  2. Store credentials in a config file (mongorc.js or a .mongorc.yaml) and protect with chmod 600.

  3. Take a consistent dump from a secondary.

    mongodump \
      --uri="mongodb://backup@mongo02.internal:27017/?authSource=admin&readPreference=secondary&tls=true&tlsCAFile=/etc/ssl/mongodb/ca.crt" \
      --oplog \
      --gzip \
      --archive=/var/backups/mongodb/dump-$(date +%F).archive.gz

    What each flag does:

    • readPreference=secondary — pull from a secondary, no load on the primary.
    • --oplog — capture the oplog tail at the end of the dump for PITR.
    • --archive=<file> — single-file output instead of a directory tree.
    • --gzip — compress BSON on the fly.
  4. Encrypt at rest if the backup leaves the host.

    mongodump --uri="..." --archive --gzip \
      | openssl enc -aes-256-cbc -salt -pbkdf2 -pass file:/etc/backup-key \
      > /var/backups/mongodb/dump-$(date +%F).archive.gz.enc
  5. Schedule with systemd timer (more controllable than cron).

    # /etc/systemd/system/mongo-backup.service
    [Unit]
    Description=MongoDB nightly logical backup
    
    [Service]
    Type=oneshot
    ExecStart=/usr/local/sbin/mongo-backup.sh
    # /etc/systemd/system/mongo-backup.timer
    [Unit]
    Description=Nightly MongoDB backup
    
    [Timer]
    OnCalendar=*-*-* 02:30:00
    Persistent=true
    
    [Install]
    WantedBy=timers.target
  6. Ship offsite immediately.

    rclone copy /var/backups/mongodb/ remote:my-backups/mongodb/ --include "*.archive.gz*"
  7. Restore drill — into a sandbox.

    # Restore the archive
    mongorestore \
      --uri="mongodb://admin@sandbox.internal:27017/?authSource=admin" \
      --gzip \
      --archive=/var/backups/mongodb/dump-$(date +%F).archive.gz \
      --oplogReplay \
      --drop

    --drop clears each collection before restoring. --oplogReplay applies the captured oplog tail so the restored state matches the end-of-dump moment.

  8. Partial restore — single database or collection.

    mongorestore --uri="..." \
      --nsInclude="orders.*" \
      --gzip --archive=dump.archive.gz

    --nsInclude and --nsExclude accept namespace patterns (database.collection).

  9. For PITR beyond the dump moment, capture continuous oplog tails to object storage between full dumps. MongoDB Inc.’s Ops Manager and the open-source percona-backup-mongodb automate this; for a manual approach, periodic mongodump --query '{ts: {$gte: <last-ts>}}' against local.oplog.rs and replay-on-restore is the pattern.

Common pitfalls

  • mongodump without --oplog on a writeable target gives an inconsistent snapshot — not even crash-consistent. Always use --oplog (which requires a replica set, even single-node).
  • The backup role does not include privileges on system.users — to restore users alongside data, take a separate dump of the admin database with a userAdminAnyDatabase-equipped role.
  • mongorestore --drop drops collections before restoring; running it against the wrong cluster wipes production data. Always sanity-check the URI before invoking.
  • A dump that completes successfully but leaves an empty BSON file for a collection usually means the source secondary fell behind the primary mid-dump and was elected for maintenance — re-run from the primary.
  • Long-running dumps from a secondary can stall replication if the secondary’s IO is consumed by the dump. Throttle with --numParallelCollections=2 on smaller hosts.

In the engagements we run, MongoDB backup pipelines use mongodump --oplog nightly against a dedicated read-only secondary, encrypted upload to object storage in a second region, weekly restore drill into a Docker container, and a Prometheus check that pages if the latest archive is over 30 hours old. Operated under Managed Operations — and for clients with strict RPO requirements, we layer continuous oplog tailing for sub-minute PITR. The companion concept piece is database-pitr.