Automatic MongoDB Database Backup and Old Backup Cleanup
This script backs up the MongoDB database and stores it in the /opt/mongoyedek folder. If there are multiple backups, it keeps the newest 2 and deletes the others.
If you are going to use this script, first set it up in your test environment and follow it for a period you find appropriate.
To prevent the server’s disk from filling up in case there are too many old backups or they are not deleted, either define a separate disk space for the address where you will take backups, or also consider moving backups to a location outside the server.
Edit the ,, fields specified for the script according to your own Db information.
Script Creation
Script Content
#!/bin/bash
IP_ADDRESS="{Ip}"
USERNAME="{Username}"
PASSWORD="{Password}"
PORT="25080"
BACKUP_DIR="/opt/mongoyedek"
# Check and Create Backup Folder
if [ ! -d "$BACKUP_DIR" ]; then
sudo mkdir -p "$BACKUP_DIR"
sudo chown $USER:$USER "$BACKUP_DIR"
fi
# Determine file name and add number
DATE=$(date +%F)
BASE_NAME="apinizer-backup-${DATE}"
index=0
# Check existing files on the same day and determine an appropriate number
while [ -e "${BACKUP_DIR}/${BASE_NAME}-${index}.archive" ]; do
index=$((index + 1))
done
BACKUP_PATH="${BACKUP_DIR}/${BASE_NAME}-${index}.archive"
# Get file names to keep last 2 files and delete
files_to_keep=$(ls -lt "$BACKUP_DIR"/*.archive | head -n 2 | awk '{print $9}')
all_files=$(ls -lt "$BACKUP_DIR"/*.archive | awk '{print $9}')
files_to_delete=$(comm -23 <(echo "$all_files" | sort) <(echo "$files_to_keep" | sort))
for file in $files_to_delete; do
echo "Deleting: $file"
sudo rm -f "$file"
done
sudo mongodump --host "$IP_ADDRESS" --port="$PORT" --username="$USERNAME" --password="$PASSWORD" --authenticationDatabase=admin --gzip --archive="$BACKUP_PATH"
echo "Backup completed: $BACKUP_PATH"
Running Script
sudo chmod +x mongodump.sh
./mongodump.sh
Automatic Execution (Cron)
If you wish, you can ensure that the script runs at a specific time or time period. Cron can be used for this.
Add the line below to the opened file.
59 23 1 * * /path/mongodump.sh
In the example usage, the script will run on the 1st day of each month at 23:59.