Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 70 ยท Replication, sharding and operations

Backup, Restore and Import/Export

Back up and restore MongoDB: mongodump and mongorestore, mongoexport and mongoimport, filesystem snapshots, point-in-time recovery and Atlas backups.

Replication keeps your database running when a server dies, but it is not a backup. If someone runs deleteMany({}) by mistake, or a bug corrupts documents, the delete and the corruption are copied to every secondary within milliseconds. A backup is a separate, older copy of the data that you can go back to. This lesson shows the tools MongoDB offers for that: mongodump and mongorestore, mongoexport and mongoimport, filesystem snapshots, point-in-time recovery and the managed backups on Atlas.

Two numbers frame every backup plan. The recovery point objective (RPO) is how much recent data you can afford to lose: one day, five minutes, nothing. The recovery time objective (RTO) is how long you can afford to be down while you restore. A nightly dump gives an RPO of up to a day, and restoring a terabyte from it may take hours. Tighter targets need snapshots plus the oplog, or a managed service.

This site has no MongoDB server, so the shell commands in this lesson are real but read-only. Two small JavaScript stand-ins make two ideas visible: how export formats keep or lose data types, and how point-in-time recovery replays a log on top of a snapshot. They are teaching models, not the real tools.

Pick the right tool

mongodump Binary backup of data and index definitions.
mongoexport JSON or CSV, for people and other tools.
Snapshots Copy the disk. Fast for big databases.
PITR Snapshot plus oplog, back to any second.
1 / 2

mongodump and mongorestore

mongodump connects to a server and writes its data as BSON files. For each collection it creates a .bson file (the documents in their exact types) and a .metadata.json file (the options and index definitions). mongorestore reads those files and writes them into a server, rebuilding the indexes from the metadata.

Terminal
# Dump one database into a dated folder
mongodump --uri="mongodb://localhost:27017" --db=shop --out=/backups/2026-11-06

# The folder now contains:
#   /backups/2026-11-06/shop/products.bson
#   /backups/2026-11-06/shop/products.metadata.json
#   /backups/2026-11-06/shop/orders.bson
#   ...

# Restore it into another (or the same) server
mongorestore --uri="mongodb://localhost:27017" --db=shop_copy /backups/2026-11-06/shop

Options you will use often:

  • --gzip compresses each file, and --archive=shop.gz writes everything into a single file (or to stdout, so it can be piped over SSH).
  • --collection and --query limit what is dumped; --nsInclude and --nsExclude on mongorestore pick namespaces such as shop.products or shop.*.
  • --drop on mongorestore drops each collection before restoring it. Without it, restoring into an existing collection adds documents, and documents with an _id that already exists are skipped with duplicate key errors.
  • --nsFrom and --nsTo rename a database or collection during a restore.

A few limits matter. The dump reads through the normal query path, so it competes with your application and pushes your working set out of memory. On a busy primary, dump from a secondary (--readPreference=secondary in the connection string). It is a logical backup: it reads documents one by one and, on restore, inserts them again and rebuilds every index, so for multi-terabyte databases both directions get slow. A dump of a live system is also not one consistent moment, because writes continue while collections are read. On a replica set you fix this with --oplog:

Terminal
mongodump --uri="mongodb://db1.example.com:27017/?replicaSet=rs0" --oplog --gzip --out=/backups/full

mongorestore --oplogReplay --gzip /backups/full

--oplog records the oplog entries written during the dump, and --oplogReplay replays them at the end of the restore, so the result matches one point in time (the moment the dump finished). It works on a full dump of a replica set (not with --db or --collection) and not for a sharded cluster, where you need a coordinated approach (see snapshots below). Remember that the local database is never dumped, and users and roles live in the admin database, so add --db=admin or --dumpDbUsersAndRoles if you need them.

mongoexport and mongoimport

mongoexport writes JSON or CSV text, one document per line. It exists to move data between MongoDB and other tools: a spreadsheet, a script, another database. It is not a backup tool. Text formats cannot hold every BSON type unless they use Extended JSON, and the tool offers no consistency guarantees or index handling.

Terminal
# JSON lines of expensive products
mongoexport --uri="mongodb://localhost:27017" --db=shop --collection=products \
  --query='{"price": {"$gt": 10}}' --out=expensive.json

# CSV needs the field list
mongoexport --uri="mongodb://localhost:27017" --db=shop --collection=products \
  --type=csv --fields=name,price --out=products.csv

mongoimport reads JSON, CSV or TSV into a collection:

Terminal
# A file with one JSON document per line
mongoimport --uri="mongodb://localhost:27017" --db=shop --collection=products --file=expensive.json

# A single JSON array
mongoimport ... --file=products.json --jsonArray

# CSV whose first line holds field names
mongoimport ... --type=csv --headerline --file=products.csv

# Update existing documents that match on sku, insert the rest
mongoimport ... --file=update.json --mode=upsert --upsertFields=sku

The CSV caveat is that every value arrives as a string, or as a number if it looks like one, unless you declare types with --columnsHaveTypes. JSON has its own caveat, explained next.

The first TryIt: what JSON does to your types

BSON has types that plain JSON does not: ObjectId, Date, 32-bit and 64-bit integers, doubles and Decimal128. Extended JSON encodes them as small objects such as {"$oid": "..."} or {"$date": "..."}. It comes in two flavors. Relaxed mode writes ordinary JSON numbers where it can, which is readable but loses the difference between an int and a long when the number is small. Canonical mode wraps every number in a typed object, which is verbose but exact. The stand-in below writes the same document in three ways and reads each back, so you can compare the types before and after.

JS Export formats and type fidelity

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the three reports. Plain JSON turns everything into strings and numbers: the ObjectId, the date and the decimal all come back as strings, and even the original numeric types are gone. Relaxed Extended JSON keeps ObjectId, Date and Decimal128, but the small long (42) comes back as an int, because the text 42 carries no type. Canonical keeps every type. The lesson for real tools: for backups use mongodump (BSON keeps all types), and when you must use JSON for exchange, choose canonical format (--jsonFormat=canonical on mongoexport) if types matter.

Snapshots

A snapshot copies the data files at the storage level: an LVM snapshot, a cloud disk snapshot (EBS, Azure managed disks, Google persistent disks) or a storage-array snapshot. A snapshot takes seconds or minutes regardless of database size and restores quickly, because you attach the disk and start mongod. That is why it is the usual method for large databases.

The rules for a consistent snapshot:

  • If the data files and the journal are on the same volume and the volume snapshot is atomic, the WiredTiger journal makes the snapshot consistent and mongod recovers from it like from a crash.
  • If data and journal are on different volumes, or the snapshot is not atomic, first flush and block writes with db.fsyncLock(), take the snapshot, then run db.fsyncUnlock().
  • Snapshot a secondary (or a hidden member) so the primary is not affected.
  • A sharded cluster needs snapshots of every shard and the config servers taken at about the same moment. This is hard to do by hand: stop the balancer and use a coordinated tool or a managed service.

Point-in-time recovery

A nightly snapshot restores the world as of last night. If the mistake happened at 14:32 and the snapshot was at 02:00, you would lose 12 hours of orders. Point-in-time recovery (PITR) combines a snapshot with the oplog: restore the snapshot, then replay oplog entries up to a chosen moment, just before the mistake.

For this you need a continuous copy of the oplog stored outside the cluster (the oplog inside the cluster is capped and gets overwritten). The managed and enterprise tools do this for you; with open-source tools the replay step looks like this:

Terminal
mongorestore --oplogReplay --oplogLimit 1767618729:1 /backups/full

--oplogLimit takes a timestamp in seconds:ordinal form (seconds since 1970) and stops the replay before that point. Percona Backup for MongoDB, MongoDB Ops Manager/Cloud Manager and Atlas all provide PITR on top of this mechanism.

The second TryIt: snapshot plus oplog replay

The stand-in below keeps a snapshot from 02:00 and a log of operations during the day. At 14:32:10 a bad delete removes the pending orders. The restore function replays the log up to a target time. Compare restoring only the snapshot, restoring to just after the bad delete, and restoring to just before it.

JS Point-in-time recovery by replaying a log

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Restoring to 14:32:09 gives back orders 3, 4 and 5 and also keeps order 2's payment from 11:40, which a plain snapshot could never do. The practical recipe after a bad delete is to restore to just before it into a separate cluster, copy the lost documents back into production, and leave production running. Overwriting the live database with an old state would discard everything after the mistake, which is usually worse.

Atlas and managed backups

On MongoDB Atlas, dedicated clusters (M10 and larger) have Cloud Backup that takes snapshots using the cloud provider's snapshot system, on a schedule with a retention policy you set. You can add Continuous Cloud Backup for point-in-time restores within a retention window. A restore creates a new cluster or restores into an existing one, from the Atlas UI or API. Free and shared tiers do not offer the same backup features, so check your tier on the Atlas pricing page, and use mongodump for those (MongoDB Atlas Overview lists the tiers).

A practical backup plan

  • Decide RPO and RTO first, then pick tools. Daily dumps suit small databases; snapshots plus oplog suit large ones.
  • Follow 3-2-1: three copies, on two kinds of storage, one off-site. Cloud object storage with versioning and a retention lock protects against ransomware and mistakes.
  • Encrypt backups and restrict who can read them. They contain everything. See Securing a Deployment.
  • Back up from a secondary or hidden member, and monitor the backup job: a silent failure is the worst failure.
  • Test restores regularly, timing them. The restore time you measure is your real RTO.
  • Back up configuration too: users and roles, config files, and for sharded clusters the config servers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a replica set not a replacement for backups?

    Replication copies every change, including accidental deletes and corruption. A backup is an older, separate copy you can return to.
  2. 2. Which tool should you choose for a faithful backup that keeps all BSON types and index definitions?

    mongodump writes BSON and metadata.json files that mongorestore reads back with exact types and index definitions. mongoexport is for exchange, not backup.
  3. 3. A relaxed Extended JSON export contains the number 42 for a field that was an Int64. What can happen on import?

    Relaxed mode writes plain numbers, so small longs and ints look the same. Canonical mode wraps numbers in typed objects such as {"$numberLong": "42"}.
  4. 4. What does point-in-time recovery combine?

    You restore a snapshot and then apply oplog entries until just before the mistake. The oplog copy must be kept outside the cluster because the live oplog is capped.
  5. 5. After a bad deleteMany at 14:32, what is usually the safest recovery approach?

    A separate restore lets you recover only what was lost without discarding everything written after the mistake.

Summary

  • Replication is not a backup. Define your RPO (acceptable data loss) and RTO (acceptable downtime) first.
  • mongodump and mongorestore make logical BSON backups with index definitions; --oplog and --oplogReplay make a replica-set dump consistent.
  • mongoexport and mongoimport move JSON or CSV between systems; they are not backups, and relaxed Extended JSON can change number types.
  • Filesystem or cloud snapshots are fast for large data; take them from a secondary and use fsyncLock if the snapshot is not atomic.
  • Point-in-time recovery restores a snapshot and replays the oplog to a chosen moment, ideally into a separate cluster.
  • Test your restores, keep off-site encrypted copies, and on Atlas use Cloud Backup with continuous backup where available.

Next, take a tour of the hosted option in MongoDB Atlas Overview.