Tag Archives: shell script mongo

Automated MongoDB backup

I recently had to setup an automated job to backup some mongo databases. Here it is how you do it.

1. Create users for each db that needs to be backed up with full rights in that database. Pay attention to NOT create the user in admin database and allow full rights for all other user db’s. Even if you will be able to connect with that user and query the collections for other databases, you will not be able to use mongodump.

2. Write in shell file with .sh extension following script:

# Dump Mongo Dbs database every night using mongodump
# Author: by yrushka.com


## Binary path ##

echo $BAK

/usr/bin/mongodump  --port 27017 --username user1 -password user1pass --db db1 --out $BAK/`date +"%Y_%m_%d__"`db1
/usr/bin/mongodump  --port 27017 --username user2 -password user2pass --db db2 --out $BAK/`date +"%Y_%m_%d__"`db2
/usr/bin/mongodump  --port 27017 --username user3 -password user3pass --db db3 --out $BAK/`date +"%Y_%m_%d__"`db3

3. Create a task in CRON that will execute the above script to a specific schedule.

And that’s it.