Backup MongoDB Database

Simple bash script to backup MongoDB database from production server to another backup server

Create directories:

$ mkdir ~/dump
$ mkdir ~/script_backups

Create base script, like backup-db.sh:

$ touch ~/scipt_backups/backup-db.sh
$ chmod +x ~/script_backups/backup-db.sh

Edit add script bash:

$ vim ~/script_backups/backup-db.sh
#!/bin/bash

# Add your backup dir location
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/home/user/dump"

# Dump each database
mongodump -d dbname -o $BACKUP_DIR/dbname-$DATE

# Compress output dir backup
cd $BACKUP_DIR
tar -cf - dbname-$DATE | xz -9 -c - > dbname-$DATE.tar.xz

# Delete output dir backup
rm -rf $BACKUP_DIR/dbname-$DATE

# Send backup to another server
rsync -azvvPr dbname-$DATE.tar.xz [email protected]:~/backup-db

# Delete files older than 3 days
find $BACKUP_DIR/* -mtime +3 -exec rm {} \;

Finally set crontjob:

00 01 * * *     sh /home/user/script_backups/backup-db.sh