It's a simple script made with PowerShell to create a backup of a MongoDB database and save all collections in a .zip
folder or .gz
file.
1. Verify the version of MongoDB, running:
mongod --version
2. If the version of your MongoDB is 4.4 or above, you will need to install de mongodump, mongorestore, and other tools separately. For this, follow this guide: Installing the Database Tools on Windows
Note
"Starting with MongoDB 4.4, the MongoDB Database Tools are now released separately from the MongoDB Server..."
3. After the installation or if your version already has the database tools (like in version 4.2), run the following commands to guarantee that the tools are accessible by the command line:
mongodump --help
mongorestore --help
Note
If they are not accessible, follow this guide: Make the DB Tools available in your PATH
4. After all the process of installation/verification we will create the flow properly
4.1 Edit the backupMongoDatabase.ps1 script, modifying the variables:
$databaseName = "databaseName"
$mongoDbHost = "localhost:27017"
$backupPath = "C:\Path\To\Back\Folder"
Note
If the database requires authorization remember to use the command with -u and -p flags
4.2. Edit the createSystemScheduledTask.ps1 script, modifying the variable with the path of the backupMongoDatabase script and the time that the task will run
$scriptToExecutePath = "C:\Path\To\backupMongoDatabase.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 1am
Note
Change the 'databaseName' in the name and description too, for more control of which database that task will back up
4.3. Finally, open the PowerShell as admin (for precaution) and enter in the folder that the createSystemScheduledTask.ps1 is
cd "C:\Path\To\WhereScriptIs"
4.4. And execute it
./createSystemScheduledTask.ps1
4.5. The following output will be shown
5. ✅ Success! We created a basic backup task. You can check the task in Task Scheduler too:
The task:
6. Test if the task is running correctly executing it manually:
Start-ScheduledTask -TaskName 'MongoDB Backup - <databaseName>'
Take a look at this discussion at DBA Stack Exchange: How restore a specific database from backup using mongorestore command