Created
April 1, 2023 13:31
-
-
Save 247software-sanket-gandhi/e936722e0594c0aee5a688a5f8642982 to your computer and use it in GitHub Desktop.
Mongo exports all collections of a database into JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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