Skip to content

Instantly share code, notes, and snippets.

@247software-sanket-gandhi
Created April 1, 2023 13:31
Show Gist options
  • Select an option

  • Save 247software-sanket-gandhi/e936722e0594c0aee5a688a5f8642982 to your computer and use it in GitHub Desktop.

Select an option

Save 247software-sanket-gandhi/e936722e0594c0aee5a688a5f8642982 to your computer and use it in GitHub Desktop.
Mongo exports all collections of a database into JSON
#!/bin/bash
HOST="127.0.0.1"
PORT="27017"
DB_NAME="dev"
# get a list of all collections in the database
collections=$(mongosh --host $HOST:$PORT --eval "db.getCollectionNames().join('\n')" --quiet $DB_NAME)
echo $collection
# loop through each collection and export it to a JSON file
while read -r collection; do
echo "Exporting $collection..."
# replace quotes and commas in the collection name
filename="${collection//\'/}.json"
filename="${filename//,/}"
# export the collection to JSON
mongoexport --host $HOST:$PORT --db $DB_NAME --collection "$collection" --out "./$filename"
done <<< "$collections"
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment