Skip to content

Instantly share code, notes, and snippets.

@mkjsix
Created March 8, 2022 08:45
Show Gist options
  • Save mkjsix/76ccea0af054d9116ee826b3f1a58a69 to your computer and use it in GitHub Desktop.
Save mkjsix/76ccea0af054d9116ee826b3f1a58a69 to your computer and use it in GitHub Desktop.
A bash script to export all MongoDB collections from a single database to JSON files
#!/bin/bash
if [ ! $1 ]; then
echo " Example of use: $0 database_name [dir_to_store]"
exit 1
fi
db=$1
out_dir=$2
if [ ! $out_dir ]; then
out_dir="./"
else
mkdir -p $out_dir
fi
collections=`mongo --eval "print(db.getCollectionNames())" --quiet $db`
for c in ${collections//,/ }
do
echo "==> Exporting collection: '$c'"
mongoexport -d $db -c $c -o "$out_dir/${db}_${c}.json"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment