Created
January 29, 2020 11:31
-
-
Save justsml/b18389deea9cd535338b9468213126ea to your computer and use it in GitHub Desktop.
Export all collections in a mongo database to JSON files!
This file contains hidden or 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 | |
set -euo pipefail | |
IFS=$'\n\t' | |
PARAMS="" | |
DB_HOST="localhost" | |
DB_PORT=27017 | |
DB_DATABASE="local" | |
# DB_COLLECTION="" | |
DATE_STAMP="$(date +%F)" | |
while (( "$#" )); do | |
case "$1" in | |
-h|--host) | |
DB_HOST=$2 | |
shift 2 | |
;; | |
-p|--port) | |
DB_PORT=$2 | |
shift 2 | |
;; | |
-d|--db) | |
DB_DATABASE=$2 | |
shift 2 | |
;; | |
# -c|--collection) | |
# DB_COLLECTION=$2 | |
# shift 2 | |
# ;; | |
--) # end argument parsing | |
shift | |
break | |
;; | |
--*=|-*) # unsupported flags | |
echo "Error: Unsupported flag $1" >&2 | |
exit 1 | |
;; | |
*) # preserve positional arguments | |
PARAMS="$PARAMS $1" | |
shift | |
;; | |
esac | |
done | |
eval set -- "$PARAMS" | |
if [[ -z "$DB_DATABASE" ]]; then | |
printf "ERROR!\\n usage: %s --db <database>\\n" "$0" && exit 1 | |
fi | |
COLLECTIONS=$(mongo "$DB_DATABASE" --quiet --eval 'db.getCollectionNames().forEach(printjson)') | |
# xargs --delimiter=\n echo mongoexport --db "$DB_DATABASE" --collection "{}" --jsonArray --out="$DB_DATABASE-{}-test.json" | |
echo "Exporting $DB_DATABASE Collections: $COLLECTIONS" | |
sleep 5s | |
for c in $COLLECTIONS | |
do | |
# c=$(echo ${c//"/}) | |
c="${c//\"/}" | |
mongoexport --db "$DB_DATABASE" --port "$DB_PORT" --host "$DB_HOST" --collection "$c" --jsonArray --out="$PWD/$DB_DATABASE-$c-$DATE_STAMP.json" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment