Tuesday, July 11, 2017
MongoDB provides excellent support for redundancy and reliability with replica sets and sharding. But what if you just want a daily backup of all your data on the entire MongoDB server?
Backing up your data on a daily basis has a few advantages:
I create a daily backup of my local every day in-case I break something in my mongo instance. On my current project, we are always working and testing Sitecore Contact cards.
I have a simple windows batch script I run with a simple windows scheduled task that will backup all mongodb databases and collections into a daily folder. This script leverages mongodump.exe. I placed this script in my mongodb bin folder, as a sibling to mongodump.exe: C:\Program Files\MongoDB 2.6 Standard\bin\backup.bat
This script will create a new folder C:\backups\mongodb\yyyyMMdd and dump all the mongodb collections into this folder. Each database will have its own subfolder, and inside each folder will contain .bson files that represent each collection:
NOTE: If you run this script more than once in a day, it will overwrite the previous backup. If you need to run a backup more than once a day, modify the script to your liking.
Then you can set it up as a windows schedule task to run every day. I run mine at 3AM. However, this backup runs within a few seconds even with gigs of data so you could run it during the day with minimal impact if you turn your machine off at night.
To restore a backup, you can use the mongorestore command:
1 mongorestore <path to the backup>
For more information on MongoDB backups and restores, including parameters to these commands like the port number, I recommend reviewing the official documentation. Have fun scripting!