Backup Restore MongoDB Database on CentOS 8

In this tutorial, we shall see how to backup restore MongoDB database on CentOS 8.

MongoDB classified as a NoSQL database program and it is scalable, robust, reliable, and easy to use.


Backup restore MongoDB database on CentOS 8

To backup data, we should use the command mongodump. For restoring, use mongorestore. Let’s see how they work.

Backup database using mongodump command

The argument of the command is mongodump <options> <connection-string>. We are using argument for backup is mongodump –db.

First, create a backup directory, where you can store all your database backups. Use following command to create a directory:

# mkdir -p /var/backup/mondodbbackups

Note: You can set the name of the directory as per your choice.

Now, run mongodump command to export the database and store into human readable format.

# mongodump –db database_name –out /var/backups/mondodbbackups/`date +”%m-%d-%y”`

Replace database_name to your database name that you want to take backup.


2020-12-01T23:26:46.362-0500 writing database_name.system.version to
2020-12-01T23:26:46.364-0500 done dumping database_name.system.version (1 document)

The path of the directory we have set is `date +”%m-%d-%y”`. It will automatically gets the current date and set to the directory name.

You can take backup regularly using crontab. Add the dump command into crontab and set the timing like shown below

2 4 * * * mongodump –db database_name –out /var/backups/mondodbbackups/`date +”%m-%d-%y”`

Above command will take backup regularly on the certain time we have set. It will take the backup of the mentioned database. If you want to take all database backup omit the –db and database_name and add remaining command.

If you want to remove all the backups older than seven days or as per your choice, you can use following bash command:

# find /var/backups/mondodbbackups/ -mtime +7 -exec rm -rf {} \;

You can add above command into crontab similarly mongodump command and make this task automatically.

Restore a MongoDB database using mongorestore command.

For restoring MongoDB, we’ll use the command mongorestore, which works with the binary backups that mongodump produces.

Let’s continue our examples with the database_name database and see how we can restore it from the previously taken backup. We’ll first specify the name of the database with the –nsInclude argument. We’ll be using database_name.* to restore all collections. To restore a single collection such as restaurants, use database_name.restaurants instead.

Then, using –drop, we’ll make sure that the target database is first dropped so that the backup is restored in a clean database.

# mongorestore –db database_name –drop /var/backups/mondodbbackups/12-01-20/database_name/

We have successfully restored the MongoDB database.

In this tutorial, we have seen how to backup restore MongoDB database on CentOS 8.

Related Articles