Skip to content

Instantly share code, notes, and snippets.

@hilbix
Created March 9, 2018 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hilbix/8f768dfe80638ad8a03340b92cd17b30 to your computer and use it in GitHub Desktop.
Save hilbix/8f768dfe80638ad8a03340b92cd17b30 to your computer and use it in GitHub Desktop.
Export complete MongoDB as JSON files with one record a line
#!/bin/bash
#
# mongoexportall [directory [connection-options..]]
#
# This Works is placed under the terms of the Copyright Less License,
# see file COPYRIGHT.CLL. USE AT OWN RISK, ABSOLUTELY NO WARRANTY.
# (CLL is more free than Public Domain, as it disallows Copyrights.)
OOPS() { { printf 'OOPS:'; printf ' %q' "$@"; printf '\n'; } >&2; exit 23; }
DIR="${1:-export}"
CONN=("${@:2}")
M()
{
mongo --quiet "${CONN[@]}" "$@"
}
Mall()
{
M --eval "[for (a of db.getMongo().getDBNames()) if (a!='local') for (b of db.getMongo().getDB(a).getCollectionNames()) if (b!='system.indexes') (a+'\t'+b)].join('\n')"
}
mkdir "$DIR" || OOPS "$DIR" exists
trap 'rmdir "$DIR" 2>/dev/null' 0
while IFS=$'\t' read -ru6 db coll
do
mongoexport "${CONN[@]}" -d "$db" -c "$coll" -o "$DIR/$db.${coll//\//--}.json"
done 6< <(Mall)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment