Mongodump cron job for nightly backup

I recently looked for a way to automatically backup Mongodb database nightly.  There are some nice bash scripts out there but I wanted to just do it in a cron job.  After some struggling with taring the huge db directory I came up with this:

0 0 * * * /bin/bash -l -c 'cd /my_project_path && mongodump --host -d mydb --username mayusername --password mypassword --out /var/dbbackups/backup_$(date +\%Y\%m\%d) && cd /var/dbbackups && tar -zcf backup_$(date +\%Y\%m\%d).tar.gz backup_$(date +\%Y\%m\%d)/mydb

The first part is the cron for midnight daily:

0 0 * * *

Then it cd's into the rails project directory and gets ready to run bash:

/bin/bash -l -c 'cd /my_project_path

Then mongodump adding the date on the dump directory:

mongodump --host -d mydb --username mayusername --password mypassword --out /var/dbbackups/backup_$(date +\%Y\%m\%d)

And finally, cd into that directory and tar (compress) the directory:

cd /var/dbbackups && tar -zcf backup_$(date +\%Y\%m\%d).tar.gz backup_$(date +\%Y\%m\%d)/mydb

Notice that I added the database name on the directory to tar.  Mongodump will create the backup_20150429/mydb directory with all of the .bson files in it.

comments powered by Disqus