Backup and Restore MongoDB

Learn how to back up and restore MongoDB databases using mongodump and mongorestore. This step-by-step tutorial covers key concepts, hands-on examples, troubleshooting, and best practices to keep your data safe.

Focus: backup and restore mongodb databases

Sponsored

Your database is gone. A botched updateMany wiped a collection, or a server disk failed at 3 a.m. Without a tested backup strategy, your data—and your reputation—evaporates. In this lesson, you'll learn how to back up and restore MongoDB databases using the trusted mongodump and mongorestore tools. By the end, you'll have a repeatable, hands-on process to protect your data and recover from disasters with confidence.

The problem this lesson solves

Data loss is not a matter of if—it's a matter of when. MongoDB stores your critical information as flexible documents, but that flexibility means nothing if you can't recover from:

  • Accidental deletions — a stray deleteMany or a misapplied filter
  • Corrupt writes — partial updates, bad imports, or failed migrations
  • Hardware failures — a crashed disk or a failed node
  • Attack or sabotage — ransomware or a disgruntled admin

Hoping it won't happen is not a strategy. A solid backup and restore process turns a potential catastrophe into a scheduled, routine operation. This lesson gives you exactly that—using MongoDB's built-in, battle-tested utilities.

Core concept / mental model

Think of mongodump and mongorestore as the snapshot-and-replay duo for MongoDB.

  • mongodump takes a point-in-time logical backup of your data and writes it to a folder of BSON files (plus JSON metadata).
  • mongorestore reads those files and replays them into a MongoDB instance—either the original or a new one.

Imagine you're a painter. mongodump is photographing your finished canvas—every brushstroke and color captured. mongorestore is using that photo to recreate the painting on a fresh canvas. The photo is your backup; the recreated canvas is your restored database.

Definitions to know

  • Logical backup — captures data at the document level (BSON), not raw disk blocks. This is portable across MongoDB versions and platforms.
  • Physical backup — copies the underlying data files. Faster for huge datasets but tied to the exact server environment.
  • Point-in-time recovery — restoring to a specific moment, often using mongodump plus an oplog replay (for replica sets).
  • Oplog — MongoDB's capped operation log in replica sets; it records every write, enabling incremental backups.

Both mongodump and mongorestore are included with the MongoDB database tools. They work with any deployment—standalone, replica set, or sharded cluster.

How it works step by step

Here's the high-level flow you'll follow every time you back up and restore MongoDB databases:

  1. Connect — point mongodump at your MongoDB instance using a connection string or host/port.
  2. Snapshot — run mongodump to export your databases (or specific ones) to a directory.
  3. Verify — check the output files (.bson and .metadata.json) to confirm the backup is valid.
  4. Store safely — copy the backup folder to a separate location (cloud storage, another disk) to protect against server loss.
  5. Restore when needed — use mongorestore to load the BSON files back into a MongoDB instance—same or new.
  6. Test periodically — practice a restore in a staging environment to ensure your backups are usable.

Backup frequency and retention

For production systems, common strategies include:

  • Daily full backups — using mongodump or filesystem snapshots.
  • Incremental backups — for replica sets, use the oplog to capture changes since the last full backup.
  • Retention policy — keep backups for a defined period (e.g., 7 daily, 4 weekly, 12 monthly) to meet compliance or recovery needs.

Pro tip: Always encrypt backups if they contain sensitive data, and store them in a different availability zone than your primary database.

Hands-on walkthrough

Let's put theory into practice. We'll back up a sample database and restore it—all from your terminal.

1. Create a sample database

If you have a running MongoDB instance (local or Atlas), create a small database to work with. Using the mongosh shell:

mongosh --quiet --eval '
  db = db.getSiblingDB("shop");
  db.products.insertMany([
    { _id: 1, name: "Laptop", price: 1200 },
    { _id: 2, name: "Mouse", price: 25 },
    { _id: 3, name: "Keyboard", price: 75 }
  ]);
'

This creates a shop database with a products collection containing three documents.

2. Run mongodump

Now back up the entire shop database to a folder named backup:

mongodump --db shop --out backup

Expected output:

2025-01-01T12:00:00.000+0000    writing shop.products to backup/shop/products.bson
2025-01-01T12:00:00.000+0000    done dumping shop.products (3 documents)

Check the files:

ls -la backup/shop/

You'll see products.bson (the data) and products.metadata.json (collection options and indexes).

3. Simulate a disaster

Drop the shop database to simulate data loss:

mongosh --quiet --eval 'db.getSiblingDB("shop").dropDatabase()'

4. Restore with mongorestore

Now bring it back:

mongorestore --db shop backup/shop

Expected output:

2025-01-01T12:01:00.000+0000    preparing metadata
2025-01-01T12:01:00.000+0000    restoring shop.products from backup/shop/products.bson
2025-01-01T12:01:00.000+0000    done restoring shop.products (3 documents)

Verify the data:

mongosh --quiet --eval 'db.getSiblingDB("shop").products.find()'

You should see all three documents restored perfectly.

5. Backup specific collections or all databases

  • Single collection: mongodump --db shop --collection products --out backup
  • All databases: just run mongodump --out backup (omit --db).
  • Restore a single collection: mongorestore --db shop --collection products backup/shop/products.bson

Compare options / when to choose what

mongodump and mongorestore are the most common tools, but they're not the only way to back up and restore MongoDB databases. Here's a comparison table to help you choose:

Method Pros Cons Best for
mongodump / mongorestore Simple, portable, works everywhere Slower for large datasets; no point-in-time recovery Small to medium databases, dev/test, cross-version migration
File system snapshots (e.g., LVM, EBS) Fast, minimal overhead Requires consistent volume; not portable Large databases, production on same infra
MongoDB Atlas Continuous Backup Managed, point-in-time recovery Vendor lock-in, extra cost Atlas users needing PITR
Oplog replay (for replica sets) Enables incremental backups Complex setup, only with replica sets Large replica sets needing PITR

Pro tip: For databases under 100 GB, mongodump is often sufficient. For massive deployments, consider filesystem snapshots or a managed backup service.

Troubleshooting & edge cases

Even straightforward backup and restore operations can hit snags. Here are common issues and how to fix them:

Connection refused or authentication failure

  • Symptom: Failed: error connecting to db server: no reachable servers
  • Fix: Check the host/port and that MongoDB is running. For authentication, use --username, --password, and --authenticationDatabase flags.
mongodump --uri "mongodb://user:pass@localhost:27017" --authenticationDatabase admin --db shop --out backup

Restore fails with --db and --collection flags

  • Symptom: When restoring a single collection, you must specify the database name even if you're restoring only one collection.
  • Fix: Use mongorestore --db target_db --collection coll_name path/to/coll.bson.

Data type mismatches after restore

  • Symptom: Numeric fields become strings or dates shift.
  • Fix: Ensure you're restoring to a compatible MongoDB version. mongodump from a newer version may not be readable by an older mongorestore. Use the --archive flag for cross-version safety.

Backup takes too long

  • Symptom: Large databases cause timeouts or excessive load.
  • Fix: Use --numParallelCollections (default 4) to balance speed and load, or switch to filesystem snapshots.

Corrupted BSON files

  • Symptom: mongorestore reports Corruption errors.
  • Fix: Always verify your backups after creation. Test restoring in a staging environment regularly—never trust a backup you haven't restored.

What you learned & what's next

You now understand how to back up and restore MongoDB databases using mongodump and mongorestore. You can protect your data from accidental deletions, hardware failures, and more. You've also learned how to compare backup methods and troubleshoot common issues.

Next step: Continue your MongoDB journey by exploring replica sets for high availability. With replica sets, you get automatic failover and the ability to use the oplog for incremental backups—taking your disaster recovery to the next level. Keep practicing, and your data will always be safe.

Practice recap

Now it's your turn. Create a sample database with a few collections, run mongodump to back it up, then drop the database and restore it using mongorestore. Verify that all documents are back. Then, try backing up only one collection and restoring it into a different database name. Repeat until the process feels automatic.

Common mistakes

  • Forgetting to specify --db when restoring a specific database—mongorestore may write to the wrong name if you point it at a folder without --db.
  • Running mongodump without authentication flags in a secured cluster—you'll get a connection error even if the server is up.
  • Not testing restores regularly—a backup that has never been restored is not a backup.
  • Restoring a backup from a newer MongoDB version into an older one, causing data type or compatibility errors.

Variations

  1. Use --archive for a single compressed backup file: mongodump --archive=backup.gz --gzip
  2. For replica sets, use --oplog to capture point-in-time changes during mongodump.
  3. Use filesystem snapshots (e.g., LVM, EBS) for large-scale production backups instead of mongodump.

Real-world use cases

  • Nightly automated mongodump of a small e-commerce database to cloud storage for disaster recovery.
  • Migrating a MongoDB database from an on-premises server to a cloud instance using mongodump and mongorestore.
  • Restoring a single collection accidentally deleted by a faulty update script, using a backup from that morning.

Key takeaways

  • mongodump creates a portable BSON backup; mongorestore replays it into any MongoDB instance.
  • Always verify your backups by performing a test restore in a staging environment.
  • Use --db and --collection flags to target specific parts of your data.
  • Choose between mongodump, filesystem snapshots, or managed backups based on database size and recovery needs.
  • Authentication and connection flags are essential for secured MongoDB deployments.
  • Incremental backups are possible with replica sets and the oplog, enabling point-in-time recovery.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.