MongoDB Auto Backup via CronJob

Vasilj Milošević // eboye
1 min readNov 25, 2017

I’m working on a project that includes working with MongoDB and it’s crucial to make DB backup daily.

I figured I could use mongodumpcommand via CronJob. So here I’m sharing with you my little bash script.

Create a directory where you are going to save your backups:

mkdir /mongodb_backups

Create a directory or choose directory where you store your scripts. I’m holding mine in folder /var/my_scripts

cd /var/my_scripts

I’m using nano as my CLI editor, so I used this command:


then paste (or type) this code:

DIR=`date +%y%m%d`
mkdir $DEST
mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o $DEST

So what the script is basically doing is making DIR name from the date. Today is 25 Nov. 2017. so the DIR name would be 171125. The it builds the path using that name in the folder /mongodb_backups. Creates that directory and executes the mongodump command. Just replace the variables in <> to suit yours. -h parameter is option if you executing script on same host as your mongodb server is. authentificationDatabase parameter is something that’s needed if you are using different table for storing your users, but for some reason even if I’m using admin table it was still needed.

Now add it to cron:

sudo crontab -e

than add at the end this line:

30 2 * * * sh /var/my_scripts/

This will execute the script every day at 2:30 … alter this line to your needs.

That’s it, enjoy! ;)