How to Backup, Restore, and Migrate MongoDB Database: A Step-By-Step Guide

How to Backup, Restore, and Migrate MongoDB Database: A Step-By-Step Guide

Database backups serve as a primary safety measure for recovering from unexpected events, such as accidental database deletions or data being overwritten during migrations. Regular backups ensure that you can quickly recover from any data loss and minimize the impact on your business operations.

In this guide, I’ll walk you through the process of creating, restoring, and migrating MongoDB database backups. You’ll learn about the essential tools and techniques involved in managing your data effectively, while also gaining insight into MongoDB-specific features that make the backup and recovery process more efficient.

MongoDB Overview

MongoDB is a leading NoSQL database that has gained popularity for its flexibility, performance, and scalability. Unlike traditional relational databases, MongoDB stores data as documents within compressed BSON files, allowing for more efficient storage and retrieval of complex data structures.

One of the key features of MongoDB is its ability to scale both vertically and horizontally, allowing it to handle large amounts of data and high-traffic loads. This is achieved through sharding, which distributes data across multiple servers, and replica sets, which provide redundancy and fault tolerance.

MongoDB also supports transactions, enabling developers to perform multiple operations in a single, atomic transaction. This ensures data consistency and integrity, even when working with distributed data.

Moreover, MongoDB is developer-friendly, with a large community and many resources available to facilitate learning and problem-solving. Some of these resources include MongoDB University, which offers free comprehensive courses on various aspects of MongoDB; MongoDB Developer Community Forums, where developers can ask questions, share resources, and engage with other members; MongoDB Compass, the official GUI for MongoDB that simplifies database management tasks; and MongoDB Atlas, the official cloud service for MongoDB that provides a fully managed, scalable, and secure database solution.

Being an open-source database, MongoDB allows for self-hosting, enabling users to deploy and manage their own MongoDB instances without the additional costs associated with cloud-based services.

Installing MongoDB Database Tools

To create backups, restore databases, and perform migrations, MongoDB provides a set of free utilities called MongoDB Database Tools.

Before we continue, you should download and install these tools by following the official guide for your operating system. Once installed, you will have access to the two CLI commands:

  • mongodump - Exports a binary copy of a database’s contents.
  • mongorestore - Loads data into a database instance.

These tools enable database backup creation, restoration, and migration.

Creating a Database Backup

Suppose you have a running MongoDB instance and need to create a backup of all the data inside. In this case, you can use the mongodump utility, which was previously installed as part of the MongoDB Database Tools.

The mongodump utility can export data from standalone deployments, replica sets, and sharded clusters.

First, let’s create a folder called backups, where we’ll store all our database backups according to a schedule (daily, hourly, etc.).

Next, open the terminal, navigate to the backups folder, and run the following command:

mongodump --uri={{CONNECTION_STRING}}

In the command above, the uri specifies the resolvable URI connection string of the MongoDB deployment. This command will create a folder called dump, which contains all the documents and index definitions (excluding the index data itself).

By default, mongodump creates a backup of all databases in the MongoDB instance. However, you might want to create a backup for a specific database or even a particular collection inside the database. In such cases, you can pass additional parameters like db, collection, or excludeCollection.

For example, to create a backup of only one database, use:

mongodump --uri={{CONNECTION_STRING}} --db={{DATABASE_NAME}}

To include only a specific collection in the backup, add the collection parameter:

mongodump --uri={{CONNECTION_STRING}} --db={{DATABASE_NAME}} --collection={{COLLECTION_NAME}}

Alternatively, to exclude specific collections from the backup, use the excludeCollection parameter:

mongodump --uri={{CONNECTION_STRING}} --db={{DATABASE_NAME}} --excludeCollection={{COLLECTION_NAME}} --excludeCollection={{COLLECTION_NAME}}

Lastly, if you want to change the default output folder name dump, pass an additional parameter called out:

mongodump --uri={{CONNECTION_STRING}} --out={{NEW_FOLDER_NAME}}

Restoring and Migrating Database

To restore a backup to the same instance or migrate it to a new instance, we’ll use the mongorestore utility, which was previously installed as part of the MongoDB Database Tools. The mongorestore utility can create a new database or add data to an existing one while also recreating indexes recorded by mongodump.

It’s important to note that mongorestore only performs inserts and does not perform updates. If restoring documents to an existing database and collection, and existing documents have the same value of _id field as the to-be-restored documents, mongorestore will not overwrite existing documents.

To use mongorestore, run the following command in the terminal:

mongorestore --uri={{CONNECTION_STRING}} --dir={{BACKUP_FOLDER_PATH}}

In the command above, the uri specifies the resolvable URI connection string of the MongoDB deployment where the backup will be restored, while dir specifies the path to the backup directory (the folder created by mongodump).

If you want to overwrite existing collections (without dropping collections that aren’t in the backup), pass an additional drop parameter:

mongorestore --drop --uri={{CONNECTION_STRING}} --dir={{BACKUP_FOLDER_PATH}}

The above command drops the collections from the target database before restoring the collections from the dumped backup.

To restore the database without indexes, pass the noIndexRestore parameter:

mongorestore --noIndexRestore --uri={{CONNECTION_STRING}} --dir={{BACKUP_FOLDER_PATH}}

If you want to restore only specific collections, pass the nsInclude parameter, which supports specifying namespace patterns:

mongorestore --nsInclude={{NAME_SPACE_PATTERN}} --uri={{CONNECTION_STRING}} --dir={{BACKUP_FOLDER_PATH}}

On the other hand, if you want to restore all collections except specific ones, pass the nsExclude parameter, which also supports specifying namespace patterns:

mongorestore --nsExclude={{NAME_SPACE_PATTERN}} --uri={{CONNECTION_STRING}} --dir={{BACKUP_FOLDER_PATH}}

Conclusion

In this guide, we have explored the importance of database backups and how to create, restore, and migrate MongoDB database backups using the MongoDB Database Tools.

By following the steps outlined, you can ensure your data is well-protected and can be recovered or migrated if something unexpected happens. With the use of the mongodump and mongorestore utilities, you gain full control over the backup process, enabling you to manage specific databases, collections, and indexes according to your needs.

Taking advantage of these tools and implementing a robust backup strategy will help you maintain the integrity and consistency of your MongoDB databases in any situation. As a result, you’ll be prepared for unexpected data loss or the need to migrate your data between different instances.