Skip to content

Instantly share code, notes, and snippets.

@zined
Created January 3, 2018 14:11
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 zined/e37d41b614099ccaf354bf709717ea5b to your computer and use it in GitHub Desktop.
Save zined/e37d41b614099ccaf354bf709717ea5b to your computer and use it in GitHub Desktop.
dump mongodb collections for database in json
#!/bin/bash
usage() {
echo "usage: ${0} database target_directory"
exit 127
}
database="${1}"
if [ -z "${database}" ]; then
usage
fi
target_directory="${2}"
if [ -z "${target_directory}" ] || [ ! -d "${target_directory}" ]; then
echo "target directory does not exist."
exit 1
fi
jsfile="$( mktemp )"
cat << EOF > $jsfile
use ${database};
show collections;
EOF
collections=$( mongo --quiet "${database}" < $jsfile | tail -n+2 )
if [ "$?" != "0" ]; then
echo "failed to get collections: $!"
exit 1
fi
for collection in $collections; do
mongoexport --db "${database}" --collection "${collection}" --out "${target_directory}/${collection}.json"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment