Skip to content

Instantly share code, notes, and snippets.

@alanning
Last active May 19, 2016 12:21
Show Gist options
  • Save alanning/8cd8a7f481efde5807af to your computer and use it in GitHub Desktop.
Save alanning/8cd8a7f481efde5807af to your computer and use it in GitHub Desktop.
Restore the latest dump of a mongo database into your local mongodb instance
#!/bin/bash
######################################################################
# Restore the latest production dump into local mongodb
######################################################################
# NOTE: Will wipe existing local destination db before restoring latest
echo "Restoring latest production dump to local mongodb"
PRODDBNAME=meteor
DUMPDIR=~/ops/dumps
LOCALDBNAME=proddump
# ensure mongodb running locally
localMongo=`ps -Ax | grep [m]ongod | head -1`
if [ "${localMongo:-null}" = null ]; then
echo " mongod must be running. Halting script."
exit 1
else
echo " local mongo found"
fi
# get filename of latest dump
LATEST=$(ls -t $DUMPDIR/mongo* | head -1)
echo " latest: $LATEST"
echo " extracting dump"
tar -vxf $LATEST -C $DUMPDIR
# get filename of latest
DIRNAME=${LATEST##*/}
# strip .tar.xz extension
DIRNAME=${DIRNAME%.*.*}
# fix up directory names
echo " renaming $PRODDBNAME to $LOCALDBNAME"
mv "$DUMPDIR/$PRODDBNAME" "$DUMPDIR/$LOCALDBNAME"
echo " wipe existing $LOCALDBNAME db"
mongo $LOCALDBNAME --eval "db.dropDatabase()"
# do mongo restore to '$LOCALDBNAME' database
echo " restoring to mongodb/$LOCALDBNAME"
mongorestore $DUMPDIR/$LOCALDBNAME > out.log
# remove existing dump
echo " cleaning up $DUMPDIR/$LOCALDBNAME"
rm -rf "$DUMPDIR/$LOCALDBNAME"
@alanning
Copy link
Author

alanning commented Oct 3, 2014

Very convenient to use with rsync. Only tested on OSX.

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