MongoDB is a popular NoSQL database known for its flexibility, scalability, and ease of use. However, to protect our data from potential data loss or corruption, it’s critical to have a reliable MongoDB backup strategy in place.
In this article, we will go through the process of creating a MongoDB dump using the powerful mongodump
tool, ensuring that our MongoDB database backup is secure and easy to restore in case of failure.
How to Create a MongoDB Dump of Database?
Data loss or corruption can occur for various reasons such as hardware failure, human error, or software bugs. Regularly backing up our MongoDB database is essential to minimize these risks. One of the best ways to backup your MongoDB database is by creating a MongoDB dump using the mongodump
tool. Below are the steps that help us to create a backup for an entire server are as follow:
- Create Direct Backups Using Mongodump
- Backup a Remote MongoDB Instance
- Backup a Secure MongoDB Instance
- Select Databases & Collections
- Change the Backup Directory
- Create an Archive File
- Compress the MongoDB Backup
- Restore Database
Step 1: Create Direct Backups Using Mongodump
We can run the mongodump command using the below syntax from the system command line as follows:
mongodump <options> <connection-string>
This structure also permits us to connect to a Mongo database with the –uri command along with a formatted string or flag such as –user, –db, and –password. However, we can’t use more than 1 flag in a single command.
Alternatively, we can use the default configurations and create a Mongo Backup via Mongodump command as follows:
Mongodump
This statement operates on the assumption that your database resides in localhost (127.0.0.1), uses port 27017, and requires no access authentication. This backup process creates a dump folder directly in the current directory as shown in the below image.
mongodumpStep 2: Backup a Remote MongoDB Instance
As mentioned in Step 1, you can customize a host and a port number with the –uri connection string using the following syntax:
mongodump --uri="mongodb://<host URL/IP>:<Port>" [additional options]
Moreover, you can set up a server connection with the host option using the following command:
mongodump --host="<host URL/IP>:<Port>" [additional options]
If you also wish to specify the port number, implement the following statement:
mongodump --host="<host URL/IP>" --port=<Port> [additional options]
The following code demonstrates the process of backing up a remote MongoDB instance:
mongodump --host="10.10.10.59" --port=27017
Output:
OutputStep 3: Backup a Secure MongoDB Instance
MongoDB’s Mongodump command allows you to implement access control mechanisms for your data backups. This will require you to provide a Username, Password, and specific Authentication options in the following syntax:
mongodump --authenticationDatabase=<Database> -u=<Username> -p=<Password> [additional options
For instance, we can use a Username & Password to connect to a remote MongoDB instance using the following command:
mongodump --host=10.10.10.59 --port=27017 --authenticationDatabase="admin" -u="barryadmin" -p="testpassword"
Output:
OutputStep 4: Select Databases & Collections
In Step 3 you learned how to back up a remote database using Mongodump. This step involves the –db and –collection options that indicate a database and a collection that requires backing up. You can run the –db option in a standalone manner, but to execute a collection, you have to specify a database. Moreover, you can remove a collection from the backup process, by using the –excludeCollection option.
To select a particular database use the following command:
mongodump --db=<Backup Target - Database> [additional options]
If you wish to select a whole collection, execute the following:
mongodump --db=<Backup Target - Database> --collection=<Collection Name> [additional options]
To exclude a particular collection, run the following command:
mongodump --db=<Backup Target - Database> --excludeCollection=<Collection Name> [additional options]
Step 5: Change the Backup Directory
We can use the –out option to specify the backup folder’s location in the following way:
mongodump --out=<Directory Location> [additional options]
Now, if we wish to switch the backup directory with the “dbbackup” folder, run:
mongodump --host=10.10.10.59 --port=27017 --authenticationDatabase="admin" -u="barryadmin" -p="testpassword" --out=dbbackup
Output:
BackupDirectoryStep 6: Create an Archive File
The Mongodump utility provides us with a method to create an archive file. We can use the –archive option for specifying the file to be archived. In case no specification is given, the output will be in the standard form (stdout).
Keep in mind that you can’t use the –archive option along with the –out option.
mongodump --archive=<file> [additional options]
You can easily define any archive file using the following command:
mongodump --host=10.10.10.59 --port=27017 --authenticationDatabase="admin" -u="barryadmin" -p="testpassword" --archive=db.archive
Output:
OutputStep 7: Compress the MongoDB Backup
Now, since you know how to backup data using Mongodump, it’s time to understand the process of compressing these files. You can use the –gzip option to compress the JSON and BSON files individually using the following command:
mongodump --gzip [additional options]
For instance, the below statement will compress a complete Mongo database:
mongodump --host=10.10.10.59 --port=27017 --authenticationDatabase="admin" -u="barryadmin" -p="testpassword" --gzip
Output:
OutputStep 8: Restore Database
Apart from excellent backups, MongoDB also provides us the facility to restore our data. The Mongorestore command will seamlessly load data from the Mongodumb backups and restore our Mongo database. The mongorestore command, however, can not overwrite documents present in the database if the id for the document already exists. Otherwise, Mongorestore will generate a new database or will add data to the existing one.
The Mongorestore command requires you to mention the path to your dump directory and the syntax is s follows:
mongorestore dump/
Moreover, in the Mongostore command:
- We must specify the –uri flag or provide every standard connection flag.
- We can directly use the most preferred –nsInclude option to restore different collections. It allows users to choose a namespace when restoring the collections for a database.
For instance, in the following command, you can isolate and import the db1 database to restore it in your local environment:
mongorestore --db=redbase --nsInclude="db1.*" dump/
This will restore all the collections of db1 that were earlier dumped. However, it won’t touch the data stored in db2 even both dn1 and db2 have their data stored in the same dump directory.
Benefits of Using Mongodump for MongoDB Backup
The mongodump
tool is a powerful and flexible way to create MongoDB backups. Some benefits of using mongodump
include:
- Efficient Data Backups: Whether you want to back up a single collection, query, or an entire MongoDB database,
mongodump
supports various backup strategies.
- Oplog Support: By including the oplog file, you can create a point-in-time snapshot of your MongoDB data for easy recovery.
- Small-Scale Backups:
mongodump
works exceptionally well for small MongoDB databases, and with the oplog feature, it’s ideal for incremental backups.
Conclusion
In conclusion, backing up your MongoDB database is a crucial part of database management, ensuring data safety and integrity. The mongodump tool makes it simple to create secure, efficient, and scalable MongoDB database backups, whether you're dealing with local, remote, or secure instances. Regularly backing up your data with MongoDB dumps will protect you from data loss and help ensure smooth recovery when needed.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read