Bash Script For Mongodb Backup
5/5 - (1 vote)

Last Updated on January 4, 2023 by Vikash Ekka

MongoDB is a popular, open-source NoSQL database that is designed for scalability, high performance, and ease of development. It is classified as a document database, meaning that it stores data in the form of JSON-like documents with optional schemas.

One of the key features of MongoDB is its ability to handle large amounts of data with high performance and scalability. It is designed to scale horizontally across a large number of servers, and it uses a distributed database architecture to support high throughput and low latency.

In addition to its scalability and performance, MongoDB is also known for its flexibility and ease of use. It does not require a fixed schema, meaning that documents in the same collection can have different fields and data types. This makes it easy to work with and adapt to changing requirements.

MongoDB is widely used in a variety of applications, including web and mobile applications, real-time analytics, and content management. It is supported by a large and active community of developers, and it is available on a variety of platforms, including Linux, macOS, and Windows.

For more information on MongoDB, see the MongoDB documentation.


In this article, We’ll go over how to use a simple Shell script to create automated backups for your MongoDB databases. All you have to do is create a file with the .sh extension and give it executable permission.

How MongoDB backup is important

Backing up a MongoDB database is important for a number of reasons:

  • Data loss prevention: A backup can help prevent data loss in the event of a hardware or software failure, data corruption, or other unexpected issues.
  • Disaster recovery: In the event of a disaster such as a fire or flood, a backup can help you recover your data and get your systems up and running again.
  • Compliance: Depending on your industry, you may be required to keep backups of your data for regulatory or compliance purposes.
  • Security: A backup can help protect against data loss due to unauthorized access or cyber attacks.

By regularly creating backups of your MongoDB database, you can help ensure the availability, integrity, and security of your data.

If you don’t know how to install MongoDB on Ubuntu, then follow this URL

How to Configuring MongoDB on Ubuntu 22.04 LTS

How to Uninstall MongoDB from Ubuntu 22.04 LTS

Create Administrative MongoDB User on Ubuntu 22.04 LTS

Here’s a simple Bash script that you can use to backup a MongoDB database:

#!/bin/bash

# Set the current date and time
date=$(date +"%Y-%m-%d_%H-%M-%S")

# Set the name of the backup file
filename="mongodb-backup-$date.gz"

# Set the hostname and port of the MongoDB server
hostname=localhost
port=27017

# Set the name of the database to back up
database=mydatabase

# Set the path to the backup directory
backup_dir="/path/to/backup/directory"

# Create the backup
mongodump --host $hostname --port $port --db $database | gzip > $backup_dir/$filename

# Print the backup file path
echo "MongoDB backup saved to $backup_dir/$filename"

This script will use the mongodump command to create a backup of the specified MongoDB database, and save it to a file with a name in the format mongodb-backup-YYYY-MM-DD_HH-MM-SS.gz in the specified backup directory.

To use this script, you will need to replace the following placeholders with your own values:

  • hostname: The hostname of the MongoDB server.
  • port: The port number of the MongoDB server.
  • database: The name of the database to back up.
  • backup_dir: The path to the directory where you want to save the backup file.

You will also need to have the mongodump command installed and available on your system.

Run Script Manually

To run the MongoDB backup script manually, save the above script code in a file with .sh extension. and then set the execute permission on the script.

chmod +x /backup/backup-mongo.sh

Execute the shell script as follows:

bash /backup/backup-mongo.sh

Automate Schedule MongoDB Backup Script

To schedule a MongoDB backup script to run automatically, you can use a tool such as cron on Unix-like systems or the Task Scheduler on Windows.

For example, to schedule the MongoDB backup script to run every day at 2:00 AM using cron, you can add the following line to the crontab file:

0 2 * * * /path/to/mongodb_backup.sh
  1. Open the crontab file by running the following command: crontab -e
  2. Add the following line to the file, replacing /path/to/mongodb_script.sh with the path to your backup script: 0 2 * * * /path/to/mongodb_script.sh
  3. Save and close the crontab file.

This will run the script located at /path/to/mongodb_backup.sh every day at 2:00 AM. You can adjust the schedule to suit your needs by changing the values for the minutes, hours, etc.

For more information on using cron, see the crontab man page.

On Windows, you can use the Task Scheduler to schedule the script to run at a specific time or interval. To do this, you will need to create a new task and specify the script to run.

To schedule a MongoDB backup script to run regularly on Windows, you can use the Task Scheduler.

Here’s an example of how you can use the Task Scheduler to schedule a MongoDB backup script to run daily at 2:00 AM:

  1. Open the Task Scheduler by searching for it in the Start menu.
  2. Click the “Create Task” button in the Actions pane.
  3. In the “General” tab, enter a name for the task and select the “Run whether user is logged on or not” option.
  4. In the “Triggers” tab, click the “New” button and specify the schedule for the task. For example, you can select “Daily” and specify 2:00 AM as the start time.
  5. In the “Actions” tab, click the “New” button and select the “Start a program” action.
  6. In the “Program/script” field, enter the path to the script that you want to run. For example, C:\scripts\mongodb-backup.bat.
  7. Click the “OK” button to save the task.

This will schedule the script to run daily at 2:00 AM. You can modify the schedule or other settings as needed.

For more information on using the Task Scheduler, see the Microsoft documentation.

For more information on using mongodump, see the MongoDB documentation.

Restore MongoDB backup Bash Script

To restore a MongoDB backup using a Bash script, you can use the mongorestore command. Here’s an example of a script that you can use to restore a backup from a file:

#!/bin/bash

# Set the path to the backup file
backup_file="/path/to/backup/file.gz"

# Set the hostname and port of the MongoDB server
hostname=localhost
port=27017

# Set the name of the database to restore
database=mydatabase

# Restore the backup
mongorestore --host $hostname --port $port --gzip --archive=$backup_file --db $database

echo "MongoDB backup restored from $backup_file"

This script will use the mongorestore command to restore the specified backup file to the specified MongoDB database.

To use this script, you will need to replace the following placeholders with your own values:

  • backup_file: The path to the backup file.
  • hostname: The hostname of the MongoDB server.
  • port: The port number of the MongoDB server.
  • database: The name of the database to restore.

You will also need to have the mongorestore command installed and available on your system.

For more information on using mongorestore, see the MongoDB documentation.

Bash script to Auto Delete MongoDB Backup in Two days

Here is a bash script that can be used to automatically delete MongoDB backups that are more than two days old:

#!/bin/bash

# Set the location of the MongoDB backups
backup_dir="/path/to/backups"

# Find all backups that are more than two days old
old_backups=$(find $backup_dir -type f -mtime +2)

# Loop through the old backups and delete them
for backup in $old_backups; do
  rm $backup
done

This script sets the location of the MongoDB backups using the backup_dir variable. It then uses the find command to locate all backups that are more than two days old (-mtime +2). The script stores the names of the old backups in the old_backups variable.

The script then loops through the old backups using a for loop and deletes them using the rm command.

To use this script, you will need to replace /path/to/backups with the actual path to the directory where your MongoDB backups are stored. You can then save the script as a file (e.g., cleanup_backups.sh) and run it using the bash command (e.g., bash cleanup_backups.sh).

You can also set up a cron job to run the script automatically at regular intervals. For example, to run the script every day at midnight, you can add the following line to the crontab file (using the crontab -e command):

0 0 * * * /path/to/cleanup_backups.sh

This will cause the script to run every day at midnight and delete any MongoDB backups that are more than two days old. You can adjust the schedule to suit your specific needs.

Conclusion

In this tutorial, we covered a shell script for manually and automatic backing up MongoDB databases. and restore MongoDB backup.

Please let me know in the comment box if you are facing any issue.
Happy Learning !!!

By Vikash Ekka

Hi All, My name is Vikash Ekka from India. I’m the founder and tech editor of https://www.vetechno.in. I have completed my Graduation in BCA. I love to write technical articles like Windows, Linux & MAC Tutorials, Tips, Tricks, How To fix, Tutorials About Ethical Hacking & Cyber Security Guide, and Software Review. Currently, I have been working as an IT professional since 2018.

One thought on “Bash Script For Mongodb Backup – vetechno”

Leave a Reply

Your email address will not be published. Required fields are marked *