Skip to content

MongoDB Backup Script

Description: This script performs a full backup of a MongoDB database, compresses the backup, uploads it to cloud storage using rclone, and sends

email notifications about success or failure. Designed to run on a Linux host as root or a user with sufficient privileges.

sh
#!/bin/bash

# -----------------------------
# MongoDB Backup Script
# -----------------------------

# Configuration
BACKUP_DIR="/backups/mongodb"
BACKUP_FILE="mongodb-backup.tar.gz"
MONGO_URI="mongodb+srv://username:password@cluster0.example.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
RCLONE_REMOTE="onedrive:/MongoDB_Backups"
EMAIL="youremail@example.com"
LOG_FILE="/var/log/mongodb_backup.log"

# Function to send email
send_email() {
    local subject=$1
    local message=$2
    echo -e "Subject: $subject\n\n$message" | msmtp "$EMAIL"
}

# Function to handle errors
handle_error() {
    echo "[ERROR] $1" | tee -a $LOG_FILE
    send_email "MongoDB Backup Failed ❌" "Backup process failed: $1. Check logs for details."
    exit 1
}

# Start backup process
echo "Starting MongoDB backup..." | tee -a $LOG_FILE

# Ensure backup directory exists
rm -rf $BACKUP_DIR || handle_error "Failed to remove old backup directory."
mkdir -p $BACKUP_DIR || handle_error "Failed to create backup directory."

# Perform mongodump and wait for completion
mongodump --uri="$MONGO_URI" --out=$BACKUP_DIR 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    handle_error "mongodump command failed."
fi

# Ensure mongodump generated files
if [ -z "$(ls -A $BACKUP_DIR)" ]; then
    handle_error "mongodump completed but no backup files were created."
fi

# Sync filesystem to avoid race condition
sync

# Pause to ensure all files are fully written
sleep 10

# Compress backup
tar -czf $BACKUP_DIR/$BACKUP_FILE -C $BACKUP_DIR . 2>> $LOG_FILE

# Check if tar actually created the file
if [ ! -f "$BACKUP_DIR/$BACKUP_FILE" ]; then
    handle_error "Failed to create tar archive. Ensure mongodump is complete."
else
    echo "Tar archive created successfully: $BACKUP_DIR/$BACKUP_FILE" | tee -a $LOG_FILE
fi

# Upload backup to cloud
rclone copy $BACKUP_DIR/$BACKUP_FILE $RCLONE_REMOTE --progress 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    handle_error "Failed to upload backup to cloud storage."
fi

# Send success email
send_email "MongoDB Backup Successful ✅" "MongoDB backup completed successfully and uploaded to $RCLONE_REMOTE."

echo "MongoDB backup completed successfully and notification email sent to $EMAIL." | tee -a $LOG_FILE

# Remove local backup files
echo "Removing local backup files..."
rm -rf $BACKUP_DIR