Mongodb backup script

 

Backing up your mongo databases is critical so I have written a script to do such. This script is designed to be launched as a cronjob, but you can launch it from command line just as easily.

#!/bin/bash

#
#  Robert Church
#  robert@mindbend.org
#  September 9 2011
# 
#  Backs up all mongodatabases contained in the server
#
# 0 3 * * * root /opt/mongo_backup/bin/mongo_backup.sh >> /opt/mongo_backup/log
#

 

DAY=`date "+%Y.%m.%d"`
MONGOBKDIR="/opt/mongo_backup"
MONGOBKCUR="${DAY}.mongobackup"

echo; echo "::: ${DAY} - Starting"; echo;

#
# Validate of directory exists or not before creating it
#

if [ ! -d "${MONGOBKDIR}/${MONGOBKCUR}/" ]; then
 mkdir -p ${MONGOBKDIR}/${MONGOBKCUR}/;
fi

#
# Validate directory exists before dumping to it.  Prevent snowballs.
#

if [ -d "${MONGOBKDIR}/${MONGOBKCUR}/" ]; then

 cd ${MONGOBKDIR}

 echo -n "  - Mongo Server 1 ::: "
 /usr/bin/mongodump --host localhost:27027 --out ${MONGOBKCUR}/mongo1_dump 1>>/dev/null

 echo -n "  - Mongo Server 2 ::: "
 /usr/bin/mongodump --host localhost:27017 --out ${MONGOBKCUR}/mongo2_dump 1>>/dev/null

 /bin/tar --remove-files -czf ${MONGOBKCUR}.tar.gz ${MONGOBKCUR} 1>>/dev/null

else

 echo "  - Failure ::: Unable to create ${MONGOBKDIR}/${MONGOBKCUR}/";

fi

if [ -f "${MONGOBKDIR}/${MONGOBKCUR}.tar.gz" ]; then

 echo; echo "  - Success `du -sh ${MONGOBKDIR}/${MONGOBKCUR}.tar.gz`"; echo

fi

echo "::: ${DAY} Concluded."; echo;

The script will create a directory titled 2011.09.08.mongobackup for the database to be dumped into. Once the database is dumped, the directory is tarballed and gzipped and removed. One thing to note; the script will only touch the database server you specify. If you have a cluster setup and this server goes down, it will not backup.

 

Organic chemistry is the chemistry of carbon compounds. Biochemistry
is the study of carbon compounds that crawl.
-- Mike Adams