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:
- Ability to restore the database to a previous state in case of a catastrophic event in your application or database.
- In a test environment, you can test an insert, update or delete query or script with the confidence that if you do something wrong you can quickly restore the modified data.
- Create an export of your database to migrate to another server or a co-worker.
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
@echo off setlocal enableextensions enabledelayedexpansion REM Create the new backup folder. SET "folderPath=%C:\backups\mongodb\%" SET "folderName=%date:~-4,4%%date:~-10,2%%date:~7,2%" SET "backupFolder=%folderPath%%folderName%" ECHO Backup Folder: "!backupFolder!" MKDIR %backupFolder% REM Run mongo backup into our new folder. CD C:\Program Files\MongoDB 2.6 Standard\bin mongodump --out %backupFolder% ECHO mongodump completed successfully.
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 everyday. 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:
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!