How to schedule a MongoDb backup using cron

If you are running a single standalone MongoDb database or even a replicaSet maybe it’s interesting to have a backup. If you want to create a MongoDb backups using cron keep reading.

Schedule a MongoDb backup using cron

Localhost server

If you are looking for a quite simple way to automate MongoDb backup using cron, here is one:

* 1 * * * DATE=`date +%y/%m/%d/`; mkdir -p /mongo-backup/$DATE && mongodump --out /mongo-backup/$DATE

Notes:

  • Everyday at 01:00 am
  • Example path on 10th November 2014: /mongo-backup/14/11/10/
  • In the day folders, you will find a folder per database
  • In each database folder, you will find a JSON & BSON for each collection

Remote server

In MongoDb +3.6 you can use the connection URI:

* 1 * * * DATE=`date +%y/%m/%d/`; mkdir -p /mongo-backup/$DATE && mongodump --gzip --out /mongo-backup/$DATE --uri mongodb://user:password@ip,or,domains/?replicaSet=name&authSource=admin

In my tests I had to put --uri in the last position as the last option else all next options should be ommited.

Output example

MongoDB backup output

Read more about cron or mongodump

David Burgos

Read more posts by this author.