Paramclasses Academy - Blog

Tutorials Details

←
Post 29 of 35
→

MongoDB Backup and Restore: mongodump and mongorestore Tutorial

MongoDB Backup and Restore: mongodump and mongorestore Tutorial

November 6, 2026

MongoDB Backup and Restore: mongodump and mongorestore Tutorial

Introduction

Database backup and recovery are essential parts of database administration. Every application stores important information, such as user accounts, customer records, orders, product details and business data.

If a database server fails, data is accidentally deleted or a system encounters an unexpected problem, a recent backup can help recover important information.

MongoDB provides two important command-line utilities for backup and restore operations:

  1. mongodump: Creates a backup of MongoDB databases and collections.

  2. mongorestore: Restores data from a backup created using mongodump.

These utilities are included in MongoDB Database Tools.

In this tutorial, you will learn how to install MongoDB Database Tools, create database backups, back up individual collections, restore databases, restore specific collections, use compressed backups and perform practical data recovery operations.

1. What Is MongoDB Backup?

MongoDB Backup is the process of creating a copy of database information so that it can be recovered when required.

A backup may contain:

  • Database documents.

  • Collection information.

  • Collection metadata.

  • Index definitions.

  • Other supported database information.

For example, suppose you have a database named collegeDB containing student records.

If the original database is accidentally deleted, you can use a previously created backup to restore the database.

Why Is Database Backup Important?

  1. Protects important business information.

  2. Helps recover accidentally deleted data.

  3. Supports disaster recovery.

  4. Helps during server migration.

  5. Provides protection against unexpected failures.

  6. Supports database maintenance and upgrades.

Regular backups help reduce the risk of permanent data loss.

2. What Is mongodump?

mongodump is a command-line utility provided by MongoDB Database Tools.

It connects to a running MongoDB deployment and creates a BSON-based backup of database information.

It can create backups of:

  • An entire MongoDB deployment.

  • A specific database.

  • A specific collection.

  • Selected documents using a query.

Example:

mongodump --db=collegeDB

This command creates a backup of the collegeDB database.

By default, the output is stored in a folder named dump in the current working directory.

3. What Is mongorestore?

mongorestore is a MongoDB Database Tools utility used to restore BSON backup files created using mongodump.

It connects to a running MongoDB deployment and restores the backup data.

Example:

mongorestore

This command looks for the default dump directory in the current working directory and restores its contents to the local MongoDB deployment.

You can also specify a particular backup directory:

mongorestore ./dump

Difference Between mongodump and mongorestore

mongodump mongorestore
Creates database backups Restores database backups
Exports data into BSON dump files Reads BSON dump files
Used for backup operations Used for recovery operations
Saves backup information Imports backup information

4. Install MongoDB Database Tools

Before using mongodump and mongorestore, you must install MongoDB Database Tools.

These utilities are distributed separately from the MongoDB server in current MongoDB installations.

Step 1: Check MongoDB Installation

Open Command Prompt or PowerShell.

Check your MongoDB version:

mongod --version

Check whether mongosh is installed:

mongosh --version

Step 2: Download MongoDB Database Tools

Visit the official MongoDB Database Tools download page:

https://www.mongodb.com/try/download/database-tools

Select:

  • Operating System: Windows

  • Package: ZIP

  • Version: A compatible stable release

Download the package.

Step 3: Extract the ZIP File

Extract the downloaded ZIP file.

Inside the extracted folder, locate the bin directory.

You should find executables such as:

mongodump.exe
mongorestore.exe
mongoexport.exe
mongoimport.exe
bsondump.exe
mongostat.exe
mongotop.exe

Step 4: Configure the PATH

Copy the path of the extracted bin directory.

For example:

C:\mongodb-database-tools\bin

Add this path to the Windows Environment Variables under the system or user PATH.

Open a new Command Prompt after saving the changes.

Step 5: Verify Installation

Run:

mongodump --version

Then:

mongorestore --version

If both commands display their version information, the tools are available in your terminal.

Important: Use compatible MongoDB Database Tools versions for your MongoDB deployment.

5. Connect to MongoDB Before Backup

Make sure MongoDB Server is running.

For a local MongoDB installation, the default connection address is:

mongodb://127.0.0.1:27017/

Open MongoDB Shell:

mongosh

Switch to the database:

use collegeDB

Check available collections:

show collections

For this tutorial, we will use the following database structure:

collegeDB
│
├── students
├── teachers
└── courses

You can use your existing database or create sample collections for practice.

6. Create a Backup of the Entire MongoDB Database

Now let's create a backup of the collegeDB database.

Open Command Prompt or PowerShell, not the MongoDB Shell.

Run:

mongodump --db=collegeDB

Explanation

  • mongodump starts the backup utility.

  • --db=collegeDB specifies the database to back up.

  • The default output directory is dump.

After successful execution, MongoDB creates a directory structure similar to:

dump/
│
└── collegeDB/
    │
    ├── students.bson
    ├── students.metadata.json
    │
    ├── teachers.bson
    ├── teachers.metadata.json
    │
    ├── courses.bson
    └── courses.metadata.json

The exact files depend on your database collections.

What Are BSON Files?

BSON stands for Binary JSON.

MongoDB stores documents internally in BSON format.

The .bson files contain the backed-up collection documents, while metadata files preserve collection-related information such as options and index definitions.

This backup can later be restored using mongorestore.

7. Specify a Custom Backup Location

By default, mongodump creates a dump folder in the current working directory.

You can specify a different location using --out.

Example:

mongodump --db=collegeDB --out="D:\MongoDB_Backups"

Now the backup will be stored in:

D:\MongoDB_Backups\
│
└── collegeDB\
    │
    ├── students.bson
    ├── teachers.bson
    └── courses.bson

Explanation

  • --db selects the database.

  • --out specifies the backup destination.

  • The database name becomes a folder inside the specified location.

This is useful when you want to keep database backups in a separate drive or directory.

Important: mongodump can overwrite files with matching names in an existing output directory. Use a new, dedicated backup folder for each backup run.

8. Create a Backup of a Specific Collection

Sometimes you do not need to back up the entire database.

You may only need one collection.

For example, suppose you want to back up the students collection from collegeDB.

Run:

mongodump --db=collegeDB --collection=students

Explanation

  • --db=collegeDB specifies the database.

  • --collection=students specifies the collection.

The backup will contain the selected collection rather than all collections.

To save it to a custom location:

mongodump --db=collegeDB --collection=students --out="D:\Student_Backup"

This is useful when you need to protect or transfer only selected collection data.

9. Create a Backup of All MongoDB Databases

If you want to back up all supported databases in your local MongoDB deployment, run:

mongodump

By default, the utility connects to the local MongoDB server on port 27017.

It creates a dump directory containing the backup information.

Note: The local database is excluded from the standard mongodump output. Special handling may also be required for deployments with replication or sharding.

10. Create a Backup Using MongoDB Authentication

If your MongoDB server has authentication enabled, you must connect using an authorized database user.

Example:

mongodump --db=collegeDB --username=backupUser --authenticationDatabase=admin

MongoDB prompts you to enter the password.

Explanation

  • --db specifies the database.

  • --username specifies the authenticated user.

  • --authenticationDatabase specifies the database where the user credentials are stored.

The user must have sufficient permissions to back up the selected database.

The built-in backup role provides backup privileges for self-managed deployments.

Avoid placing passwords directly in command history.

11. Create a Compressed MongoDB Backup

Large databases can require significant storage space.

MongoDB Database Tools support gzip compression.

Example:

mongodump --db=collegeDB --gzip

This creates compressed backup files in the default dump directory.

You can also specify a custom directory:

mongodump --db=collegeDB --gzip --out="D:\Compressed_Backup"

Advantages of Compression

  • Reduces backup storage requirements.

  • Makes backup files easier to transfer.

  • Helps organize large database backups.

  • Can reduce storage and transfer costs.

Remember that gzip backups must be restored with the corresponding --gzip option.

12. Create a Backup in a Single Archive File

MongoDB also supports creating an archive file using the --archive option.

Example:

mongodump --db=collegeDB --archive=collegeDB.archive

This creates a single archive file instead of separate collection files in a directory.

Create a Compressed Archive

You can combine archive output with gzip compression:

mongodump --db=collegeDB --archive=collegeDB.gz --gzip

The result is a compressed archive containing the database backup.

This approach is useful when you want to manage the backup as a single file.

13. Restore a MongoDB Database Using mongorestore

Now let's restore the database from the backup.

First, make sure MongoDB Server is running.

Open Command Prompt or PowerShell in the directory containing the dump folder.

Run:

mongorestore

This restores the backup found in the default dump directory to the connected MongoDB deployment.

Restore from a Custom Backup Directory

If your backup is stored in another location, specify its path:

mongorestore "D:\MongoDB_Backups"

The backup directory should contain the database folder and its BSON files.

Explanation

  • mongorestore starts the restore utility.

  • The path identifies the backup directory.

  • MongoDB restores the available database collections.

After successful restoration, verify the data using mongosh:

use collegeDB

show collections

Retrieve student records:

db.students.find()

You should see the restored documents.

14. Restore a Specific Database

You can restore only the database you need by using the --nsInclude option.

Example:

mongorestore --nsInclude="collegeDB.*" "D:\MongoDB_Backups"

Explanation

  • --nsInclude specifies the namespace pattern.

  • collegeDB.* matches all collections inside collegeDB.

  • The path identifies the backup directory.

This is useful when your backup contains multiple databases but you only want to restore one.

15. Restore a Specific Collection

You can restore a particular collection without restoring every collection in the database.

Example:

mongorestore --nsInclude="collegeDB.students" "D:\MongoDB_Backups"

This restores the students collection from the backup.

The --nsInclude option is useful when you need selective database recovery.

16. Restore a Database with a Different Name

Sometimes you want to restore a database under a different name.

For example:

  • Original database: collegeDB

  • New database: collegeBackupDB

You can use --nsFrom and --nsTo.

Example:

mongorestore --nsFrom="collegeDB.*" --nsTo="collegeBackupDB.*" "D:\MongoDB_Backups"

Explanation

  • --nsFrom specifies the original database and collection pattern.

  • --nsTo specifies the destination database and collection pattern.

  • * represents the matching collection names.

This allows you to restore a backup into a separate database for testing or verification.

17. Restore a Compressed Backup

If the backup was created using the --gzip option, restore it using the same compression setting.

For a compressed dump directory:

mongorestore --gzip "D:\Compressed_Backup"

For a compressed archive:

mongorestore --gzip --archive="collegeDB.gz"

MongoDB reads the compressed backup and restores its contents.

18. Restore a Database Using the --drop Option

Sometimes the target database already contains documents.

If you want to replace collections with the backup versions, you can use --drop.

Example:

mongorestore --drop "D:\MongoDB_Backups"

What Does --drop Do?

The --drop option removes each target collection before restoring the corresponding collection from the backup.

For example:

Suppose the existing students collection contains newer or unwanted records.

Using --drop causes the existing target collection to be dropped before its backup is restored.

Important Warning:

  • --drop is a destructive operation.

  • Existing target collection data can be permanently removed.

  • Collections not present in the backup are not dropped.

  • Always verify the backup and target database before running this command.

  • Never use it on production data without a tested recovery plan.

19. Verify Restored MongoDB Data

After restoration, it is important to verify whether the records were recovered correctly.

Open mongosh:

mongosh

Switch to the restored database:

use collegeDB

Display the collections:

show collections

Retrieve student documents:

db.students.find()

Count the documents:

db.students.countDocuments()

You can also open MongoDB Compass and inspect the restored database visually.

Verification helps confirm that the required collections and records are available.

20. Practical Example: Complete MongoDB Backup and Restore

Let's perform a complete practical example using a database named collegeDB.

Step 1: Create Sample Database Records

Open mongosh:

mongosh

Switch to the database:

use collegeDB

Insert sample student records:

db.students.insertMany([
    {
        name: "Rahul",
        age: 22,
        course: "MongoDB"
    },
    {
        name: "Amit",
        age: 23,
        course: "Python"
    },
    {
        name: "Priya",
        age: 21,
        course: "Java"
    }
])

Verify the records:

db.students.find()

Step 2: Create a Backup

Exit mongosh:

exit

Open Command Prompt and run:

mongodump --db=collegeDB --out="D:\MongoDB_Backups"

Step 3: Verify the Backup Files

Open:

D:\MongoDB_Backups\collegeDB\

You should find:

students.bson
students.metadata.json

Other collections, if present, will also have their corresponding backup files.

Step 4: Remove the Sample Collection for Testing

For this learning example only, open mongosh:

mongosh

Run:

use collegeDB

db.students.drop()

This removes the students collection.

Warning: Perform this destructive test only on practice data, never on important production records.

Step 5: Restore the Backup

Exit mongosh and run:

mongorestore "D:\MongoDB_Backups"

Step 6: Verify Restored Records

Open mongosh:

mongosh

Run:

use collegeDB

db.students.find()

You should now see the three student records restored from the backup.

This practical example demonstrates the complete MongoDB backup and recovery process.

21. MongoDB Backup Best Practices

Follow these practices when managing database backups.

  1. Create backups regularly.

  2. Store backups outside the main database server.

  3. Maintain multiple backup copies.

  4. Use secure storage locations.

  5. Compress large backup files when appropriate.

  6. Protect backup files with suitable access permissions.

  7. Verify backup files after creation.

  8. Perform regular restore testing.

  9. Keep backup files for an appropriate retention period.

  10. Document backup and recovery procedures.

  11. Monitor backup jobs for failures.

  12. Use consistent backup methods for production workloads.

Important Production Consideration

mongodump and mongorestore are useful for logical backups, smaller deployments and migration tasks.

However, for production systems requiring minimal disruption, consistent point-in-time recovery or large-scale recovery, consider MongoDB Atlas Cloud Backups, coordinated snapshots or other deployment-appropriate backup solutions.

A normal mongodump operation during ongoing writes may not represent a single consistent point in time. For replica set backup consistency, MongoDB supports the --oplog and --oplogReplay workflow.

22. Common MongoDB Backup and Restore Errors

Error 1: mongodump Is Not Recognized

Reason: MongoDB Database Tools may not be installed or the bin folder may not be configured in PATH.

Solution:

  • Install MongoDB Database Tools.

  • Add the correct bin directory to PATH.

  • Open a new terminal.

  • Verify using:

mongodump --version

Error 2: Connection Refused

Reason: MongoDB Server may not be running.

Solution:

  • Start the MongoDB service.

  • Check the connection URI.

  • Verify the port number.

  • Try connecting using mongosh.

Error 3: Authentication Failed

Reason: The username, password or authentication database may be incorrect.

Solution:

  • Verify the credentials.

  • Check the authentication database.

  • Confirm that the user has the required backup or restore permissions.

Error 4: Backup Directory Not Found

Reason: The specified backup path may be incorrect.

Solution:

  • Check the folder location.

  • Verify the directory name.

  • Use the complete backup path.

Error 5: Unauthorized to Perform Operation

Reason: The connected user may not have sufficient database privileges.

Solution:

Ask an authorized administrator to assign the required backup or restore permissions.

Error 6: Duplicate Key Error During Restore

Reason: Documents with the same unique _id may already exist in the target collection.

Solution:

  • Verify the existing target data.

  • Choose an appropriate restore strategy.

  • Use --drop only if replacing the target collections is intended and safe.

23. Practical Exercises

Try these exercises to improve your MongoDB backup and recovery skills.

Exercise 1: Create a database named schoolDB.

Exercise 2: Insert five student records into a collection named students.

Exercise 3: Create a complete database backup using mongodump.

Exercise 4: Save the backup in a custom directory.

Exercise 5: Create a backup of only the students collection.

Exercise 6: Create a compressed backup using --gzip.

Exercise 7: Restore the database using mongorestore.

Exercise 8: Restore only the students collection using --nsInclude.

Exercise 9: Restore the database under a different name using --nsFrom and --nsTo.

Exercise 10: Verify the restored records using find() and countDocuments().

24. Frequently Asked Questions (FAQs)

Q1. What is mongodump in MongoDB?

mongodump is a command-line utility used to create BSON-based backups of MongoDB databases and collections.

Q2. What is mongorestore in MongoDB?

mongorestore is a utility used to restore MongoDB data from backups created using mongodump.

Q3. Are mongodump and mongorestore included with MongoDB Server?

They are provided through MongoDB Database Tools, which are distributed separately from current MongoDB Server installations.

Q4. How do I back up a MongoDB database?

Use:

mongodump --db=collegeDB

Q5. How do I restore a MongoDB database?

Use:

mongorestore

This restores from the default dump directory.

Q6. Can I back up only one collection?

Yes. Use:

mongodump --db=collegeDB --collection=students

Q7. Can I compress MongoDB backups?

Yes. Use the --gzip option with mongodump and the corresponding option with mongorestore.

Q8. What is the purpose of the --drop option?

It drops each target collection before restoring its backup counterpart. It should be used carefully because it can remove existing data.

Q9. Can I restore a MongoDB backup to another database?

Yes. Use --nsFrom and --nsTo to change the database or collection namespace during restoration.

Q10. Are mongodump backups suitable for every production environment?

Not necessarily. Large or highly available production systems may require coordinated snapshots or managed backup solutions for consistent and efficient recovery.

Conclusion

MongoDB Backup and Restore are important database administration skills that help protect valuable application data.

In this tutorial, we learned how to install MongoDB Database Tools, create backups using mongodump, back up entire databases and individual collections, compress backup files, create archive files and restore data using mongorestore.

We also explored selective restoration, database renaming, the --drop option, authentication, backup verification and practical recovery exercises.

By understanding these commands and following proper backup practices, developers and database administrators can protect MongoDB data and recover information when required.

Practice these examples in your local MongoDB environment to strengthen your database administration skills.

←
Post 29 of 35
→