Skip to content

Instantly share code, notes, and snippets.

@alanning
Last active July 24, 2022 23:42
Show Gist options
  • Save alanning/ac89fa86f3ac7a11f8df to your computer and use it in GitHub Desktop.
Save alanning/ac89fa86f3ac7a11f8df to your computer and use it in GitHub Desktop.
Backup script that dumps a mongo database and compresses the result. Can be run on-demand or via nightly cron job.
#!/bin/bash
# Performs a dump of target database and compresses result.
# Outputs to: $DUMPDIR/$DUMPNAME.tar.xz
# Note: Absolute paths are required for use in cron jobs
DBNAME=meteor
ROOTDIR=/Users/alanning/foo
DUMPDIR=$ROOTDIR/dumps
LOGDIR=$ROOTDIR/log
TAR=`which tar`
set -o nounset
set -o errexit
mkdir -p $DUMPDIR
mkdir -p $LOGDIR
LOGFILE=$LOGDIR/nightly-dump.log
DATE=$(date +"%Y%m%d%H%M")
DUMPNAME=mongodump-$DBNAME-$DATE
echo `date '+%Y-%m-%d %H:%M:%S'` Dumping database >> $LOGFILE
# Create raw dump
mongodump --db $DBNAME --out $DUMPDIR/$DUMPNAME >> $LOGFILE
# Archive dump
$TAR -cvJf $DUMPDIR/$DUMPNAME.tar.xz -C $DUMPDIR $DUMPNAME . 2>> $LOGFILE
# Clean up working folder
rm -r $DUMPDIR/$DUMPNAME
echo "Dump complete: $DUMPNAME.tar.xz" >> $LOGFILE
echo "" >> $LOGFILE
# Echo again so will show up in cronjob email
echo "Dump complete: $DUMPNAME.tar.xz"
@jorgeantonyo
Copy link

And to backukp all databases? What's the procedure ?

@kthallam
Copy link

kthallam commented Feb 6, 2018

We can just use command called :

monogodump

This will backup all databases including admin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment