Last active
August 31, 2015 16:33
-
-
Save GregoireHebert/21881056dccbef0ed8c2 to your computer and use it in GitHub Desktop.
Import export script for mongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
LOADING=false | |
usage() | |
{ | |
cat << EOF | |
usage: $0 [options] dbname | |
OPTIONS: | |
-h Show this help. | |
-l Load instead of export | |
-u Mongo username | |
-p Mongo password | |
-H Mongo host string (ex. localhost:27017) | |
-b Mongo BackupName | |
EOF | |
} | |
while getopts "hlu:p:H:b:" opt; do | |
MAXOPTIND=$OPTIND | |
case $opt in | |
h) | |
usage | |
exit | |
;; | |
l) | |
LOADING=true | |
;; | |
u) | |
USERNAME="$OPTARG" | |
;; | |
p) | |
PASSWORD="$OPTARG" | |
;; | |
H) | |
HOST="$OPTARG" | |
;; | |
b) | |
BACKUPNAME="$OPTARG" | |
;; | |
\?) | |
echo "Invalid option $opt" | |
exit 1 | |
;; | |
esac | |
done | |
shift $(($MAXOPTIND-1)) | |
if [ -z "$1" ]; then | |
echo "Usage: export-mongo [opts] <dbname>" | |
exit 1 | |
fi | |
DB="$1" | |
if [ -z "$HOST" ]; then | |
CONN="localhost:27017/$DB" | |
else | |
CONN="$HOST/$DB" | |
fi | |
ARGS="" | |
if [ -n "$USERNAME" ]; then | |
ARGS="-u $USERNAME" | |
fi | |
if [ -n "$PASSWORD" ]; then | |
ARGS="$ARGS -p $PASSWORD" | |
fi | |
if $LOADING ; then | |
echo "*************************** Mongo Import ************************" | |
else | |
echo "*************************** Mongo Export ************************" | |
fi | |
echo "**** Host: $HOST" | |
echo "**** Database: $DB" | |
echo "**** Username: $USERNAME" | |
echo "*****************************************************************" | |
if $LOADING ; then | |
echo "Loading into $CONN" | |
if [ -n "$BACKUPNAME" ]; then | |
tar -xzf $BACKUPNAME.tar.gz | |
pushd $BACKUPNAME>/dev/null | |
mongorestore -d $DB $BACKUPNAME | |
else | |
tar -xzf $DB.tar.gz | |
pushd $DB >/dev/null | |
mongorestore -d $DB $DB | |
fi | |
popd >/dev/null | |
rm -rf $DB | |
else | |
DATABASE_COLLECTIONS=$(mongo $CONN $ARGS --quiet --eval 'db.getCollectionNames()' | sed 's/,/ /g') | |
mkdir /tmp/$DB | |
pushd /tmp/$DB 2>/dev/null | |
for collection in $DATABASE_COLLECTIONS; do | |
mongoexport --host $HOST -u $USERNAME -p $PASSWORD -db $DB -c $collection --jsonArray -o $collection.json >/dev/null | |
done | |
mongodump --host $HOST -u $USERNAME -p $PASSWORD -d $DB -o /tmp/$DB >/dev/null | |
pushd /tmp 2>/dev/null | |
tar -czf "$DB.tar.gz" $DB 2>/dev/null | |
popd 2>/dev/null | |
popd 2>/dev/null | |
mv /tmp/$DB.tar.gz ./ 2>/dev/null | |
rm -rf /tmp/$DB 2>/dev/null | |
fi | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment