Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.