Created
April 16, 2015 21:17
-
-
Save thbkrkr/7617edf1f540a04f482a to your computer and use it in GitHub Desktop.
Export all MongoDB collections to 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 | |
DB=$1 | |
COLLECTIONS=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | sed 's/,/ /g') | |
for collection in $COLLECTIONS; do | |
echo "Exporting $DB/$collection ..." | |
mongoexport -d newtickettoolDB -c $collection -o $collection.json | |
done |
I had to use the code bellow to get the names of the collection properly
mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | tr -d '\[\]\"[:space:]' | tr ',' ' '
mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | grep \" | tr -d '\[\]\"[:space:]' | tr ',' ' '
I think this is a better solution, or you may get stuff like successfully connected to db as a collection
jq version
#!/bin/bash
DB=$1
COLLECTIONS=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | jq '. | join(" ")')
for collection in $COLLECTIONS; do
echo "Exporting $DB/$collection ..."
mongoexport -d $DB -c $collection -o $collection.json
done
For me, the last version failed due to first/last extra quotes " in the collection list.
Fixed:
#!/bin/bash
DB=$1
COLLECTIONS=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | jq -r '. | join(" ")')
for collection in $COLLECTIONS; do
echo "Exporting $DB/$collection ..."
mongoexport -d $DB -c $collection -o $collection.json
done
mongo localhost:27017/integradornfse --quiet --eval "db.getCollectionNames()"| sed 's/,/\n/g'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Small fix on this line:
mongoexport -d newtickettoolDB -c $collection -o $collection.json
needs to bemongoexport -d $DB -c $collection -o $collection.json
Thanks for the code btw :)