Did you know that MongoDB databases have a built-in backup mechanism that is accessible via shell or the mongod process? The mongod process automatically takes a snapshot every time a database transitions to another state. These different states are: starting, stopping, upgrading, and recovering after a crash. However, these snapshots won’t be enough in case of catastrophic failures such as disk corruption or natural disaster. To protect your valuable data from such threats, it is advisable to implement an automated backup strategy for your MongoDB databases.

Advertisement

In this article, we will discuss how to create automated backups for your MongoDB databases using a simple Shell script.

Shell Script for MongoDB Backup

The shell script for MongoDB database backup is available on Github. You can use the below link to get access of the shell script.

https://github.com/tecrahul/shell-scripts/blob/master/backup-mongo.sh

Alternatively, You can copy the below script and save it on your Linux system.

Run Script Manually

Save the above script in a file with .sh extension. I want to save all the backups under /the backup directory. So placed the shell script in the same directory. Then set the execute permission on the script.

chmod +x /backup/backup-mongo.sh 

Run the shell script as below:

bash /backup/backup-mongo.sh 

Schedule MongoDB Backup Script

You can easily schedule this script under crontab to backup databases regularly. To edit the crontab, run crontab -e command and append the below code:

Wrap Up

In this tutorial, we have discussed a shell script that helps to backup MongoDB databases manually. Also, you can schedule scripts to backup databases on regular basis.

Share.

2 Comments

Leave A Reply


Exit mobile version