This script takes a backup of the MongoDB database and stores it in the /opt/mongobackup folder. If there is more than one backup, it keeps the 2 most recent ones and deletes the others.

Edit the {IP},{Username},{Password} fields specified for the script according to your own DB information.

sudo vi mongodump.sh
POWERSHELL
#!/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
 
# Specify file name and add number
DATE=$(date +%F) 
BASE_NAME="apinizer-backup-${DATE}"
index=0
 
# Check existing files on the same day and set a suitable number
while [ -e "${BACKUP_DIR}/${BASE_NAME}-${index}.archive" ]; do
    index=$((index + 1))
done
 
BACKUP_PATH="${BACKUP_DIR}/${BASE_NAME}-${index}.archive"
 
# Get and delete file names to keep last 2 files
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 "Siliniyor: $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"
POWERSHELL
sudo chmod +x mongodump.sh
./mongodump.sh
POWERSHELL

If you wish, you can have the script run at a specific time or time period. Cron can be used for this.

sudo crontab -e
POWERSHELL

Add the following line to the opened file.

59 23 1 * * /path/mongodump.sh
POWERSHELL

In the example usage, the script will run at 23:59 on the 1st day of each month.