From fca3f5afe3f976d3fa60d1b6480db525d08497f7 Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Tue, 17 Jun 2025 10:39:19 +0200 Subject: [PATCH] Add MongoDB backup script with service check --- README.md | 13 +++++++++++++ scripts/backup_mongodb.sh | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 scripts/backup_mongodb.sh diff --git a/README.md b/README.md index 627f451..8b9256e 100644 --- a/README.md +++ b/README.md @@ -30,3 +30,16 @@ python src/run.py --help ``` for a description of all available options. + +## MongoDB backup script + +`scripts/backup_mongodb.sh` dumps a MongoDB database to a Dropbox-synced +folder. The script starts `mongod` if it is not running and stops it again +when the backup finishes (if it was started by the script). + +Make it executable before scheduling it with `cron`: + +```bash +chmod +x scripts/backup_mongodb.sh +``` + diff --git a/scripts/backup_mongodb.sh b/scripts/backup_mongodb.sh new file mode 100644 index 0000000..7fb692f --- /dev/null +++ b/scripts/backup_mongodb.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# scripts/backup_mongodb.sh +# Backup MongoDB database, ensuring mongod is running. + +DATE=$(date +%Y-%m-%d) +BACKUP_DIR="$HOME/Dropbox/backups" +DBNAME="DBNAME" +USERNAME="USERNAME" +PASSWORD="PASSWORD" +BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}" + +mkdir -p "$BACKUP_DIR" + +# Track whether we started mongod +started_mongod=false + +# Check if mongod process is running +if pgrep mongod >/dev/null; then + echo "mongod is running" +else + echo "mongod is not running. Starting..." + if command -v systemctl >/dev/null; then + sudo systemctl start mongod + else + sudo service mongod start + fi + started_mongod=true +fi + +# Dump the database +mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH" + +# Stop mongod if we started it +if [ "$started_mongod" = true ]; then + echo "Stopping mongod..." + if command -v systemctl >/dev/null; then + sudo systemctl stop mongod + else + sudo service mongod stop + fi +fi