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:

#!/bin/bash
# Dump Mongo Dbs database every night using mongodump
# Author: by yrushka.com

BAK="/opt/backup"

## Binary path ##
#MONGO="/usr/bin/mongo"
#MONGODUMP="/usr/bin/mongodump"

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.

  1. great quick tip. Can you please also illustrate full backup..recovery scenario for mongodb.

    thanks
    manoj

  2. hi, you could add the mongorestore command in a similar shell script and execute one after another.

  3. Great, quite simple and efficient. I used it.
    Thanks you
    Ch

  4. Thanks a tonne! I’ve been banging my head to create a cron job to dump mongodb data hourly for the last couple of hours. I was using mongodump instead of /usr/bin/mongodump.
    THIS POST LITERALLY SAVED MY LIFE.
    Thanks again.

  5. can you please let me know what’s wrong in this.I created a windows scheduler task and its not creating a backup.What is
    BAK=”/opt/backup” mean ?

    #!/bin/bash
    # Dump Mongo Dbs database every night using mongodump
    # Author: by yrushka.com

    BAK=”/opt/backup”

    ## Binary path ##
    #MONGO=”C:\Program Files\MongoDB\Server\3.2\bin\mongo”
    #MONGODUMP=”C:\Program Files\MongoDB\Server\3.2\bin\mongodump”

    echo $BAK
    mongodump –port 27017 –username “pramoda” -password “pramoda” –db “Create_Lesson_db” –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

  6. BAK is a variable which sets the path to your backup. in windows there is no /opt/ folder.
    You need to change that.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>