Timely Backups of Mongo Database

1 Min. Read
Dec 14, 2020

Related Article: Timely Backups of PG Database

Backing up and Restoring database using mongo dump and mongo restore

Let us start with basic dump and restore processes of a mongo database. The steps involved are:

Dumping DB:

  • get the name of your database if you don’t already know it, from the db list

    load mongo interactive mongo

    list dbs show dbs

    quit exit

  • dump the database using mongo_dump

    mongodump --db db_name --out /home/user/Desktop

  • access the dumped file

    cd /home/user/Desktop/db_name/

Restoring DB:

Restoring from the dumped backup file is pretty straight forward. Please Follow these steps:

  • run the mongo restore command by specifying the dump directory mongorestore --db db_name_to_restore_it_to /home/user/Desktop/db_name/

    Drop is necessary if you are replacing an existing db mongorestore --drop --db db_name_to_restore_it_to /home/user/Desktop/db_name/

That’s it.

Automatic database backups with cron

We shall be using cron to create automatic hourly backups of the database with mongo_dump as above. The file will be saved with today’s date as the filename and data will be over-written to it every hour.

The steps to do so are as follows:

  • Create a script file

    nano ~/bin/db_backup.sh

  • Edit the file’s content

    #!/bin/bash

    function date_today { date +"%F" ; }

    declare T="$(date_today)_dbname"

    mongodump --db db_name --out /home/user/backups/"${T}"/

    Here, app_production is the name of the database

  • Make the file executable

    chmod +x ~/bin/db_backup.sh

  • Add a cron task

    crontab -e

  • The task has to run every hour. Add this line

    0 * * * * ~/bin/db_backup.sh

  • Save and exit

  • Verify that the task is running at the specified time by checking the logs

    tail /var/log/syslog -f -n 100 | grep CRON

    or

    grep CRON /var/log/syslog

  • After the cron task has run, verify the existence of file on the target location

    cd /home/user/backups/backup_dir/db_name_dir/

    ls

  • Check if the directory is being overwritten to at the specified time (1 hour in our case)

    stat -c '%y' organization.json , where organization.json can be name of any file in the directory

If you don’t want data to be overwritten to the same file every hour and instead want different files for each hour, simply replace the content of function date_today in the script with function date_today { date +"%Y-%m-%d_%H:%M" ; }

Thank you for reading.