> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apinizer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Automatic Backup and Cleanup of Old Backups for MongoDB Database

> You can prevent data loss by automatically backing up MongoDB database, optimize storage space by cleaning old backups, configure scheduled backup with cron job, and perform restore operations from backup with mongodump.

<Warning>
  This script backs up MongoDB database and stores it in `/opt/mongoyedek` folder. If there are multiple backups, it keeps the newest 2 and deletes the others.
</Warning>

<Warning>
  To prevent filling the server's disk in case old backups are too many or not deleted, either define a separate disk space for the address where you will take backups or also consider moving backups to a place outside the server.
</Warning>

Edit the 'Ip,Username,Password' fields specified for the script according to your own Db information.

```bash theme={null}
sudo vi mongodump.sh
```

```bash theme={null}
#!/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 within 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"
```

```bash theme={null}
sudo chmod +x mongodump.sh
./mongodump.sh
```

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

```bash theme={null}
sudo crontab -e
```

Add the line below to the opened file.

```bash theme={null}
59 23 1 * * /path/mongodump.sh
```

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