1 Comment

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 0.0.0.0 -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 0.0.0.0 -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.

One comment on “Mongodump cron job for nightly backup

  1. If it helps any, I have a cron job that I do hourly backups to S3. Not only does it provide for backups off site, but having it on S3 andhourly makes it easier for me to test locally with close to the latest data before deploying or when working on a tough bug.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: