Automatic MongoDB backup in windows

It's a very good idea to take backups of our MongoDB periodically. We can use the following script to create a folder with current date time and dump the database in it. The script also runs 7zip and compresses the backup directory. When compression is done, this script will delete the backup directory. This will save a lot of disk space.

@echo OFF

:: This will create a timestamp like yyyy-mm-dd-hh-mm-ss.
set BACKUPNAME=E:\mongo-db-backup
set BACKUPNAME=%BACKUPNAME%\%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%-%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%

@echo BACKUPNAME=%BACKUPNAME%


:: Create a new directory
md "%BACKUPNAME%"

echo Running backup "%BACKUPNAME%"
mongodump -h localhost -d stipend_icr -u stipend_icr_user -p pr0g0t1 -o "%BACKUPNAME%"

REM ZIP the backup directory
echo Running 7zip on backup "%BACKUPNAME%"
"C:\Program Files\7-Zip\7z.exe" a -tzip "%BACKUPNAME%.zip" "%BACKUPNAME%"

REM Delete the backup directory (leave the ZIP file). The /q tag makes sure we don't get prompted for questions 
echo Deleting original backup directory "%BACKUPNAME%"
rmdir "%BACKUPNAME%" /s /q


If we add this script as a recurring scheduled task in windows, it'll create the backup on the scheduled time.

Comments

Post a Comment

Popular posts from this blog

Run tasks in background in Spring

How to configure Wildfly 10 to use MySQL

Conditional field inclusion in Jackson and Spring Boot