-
-
Save milkyklim/d0e84b0546316b6ceed1327e9801e834 to your computer and use it in GitHub Desktop.
Export all MongoDB collections as csv without specifying fields (tested only on non-empty collections with plain scheme).
This file contains 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
OIFS=$IFS | |
IFS="," | |
# fill in your details here | |
dbname=<DBNAME> | |
user=<USERNAME> | |
pass=<PASSWORD> | |
host=<HOST> | |
port=<PORT> | |
authdb=<AUTHDB> | |
# first get all collections in the database | |
collectionNames=`mongo $dbname --host $host --port $port -u $user -p $pass --authenticationDatabase $authdb --eval 'db.getCollectionNames().join('');' --quiet` | |
# uncomment for debug | |
# echo $collectionNames | |
for col in $collectionNames | |
do | |
echo 'exporting collection' $col | |
# get comma-separated list of keys | |
keys=`mongo $dbname --host $host --port $port -u $user -p $pass --authenticationDatabase $authdb --eval "rs.slaveOk(); let keys = ''; for (let key in db.getCollection('$col').findOne()) { keys += (key + ','); }; keys;" --quiet` | |
mongoexport --host $host --port $port -u $user -p $pass --authenticationDatabase $authdb -d $dbname -c $col --fields "${keys::-1}" --type=csv --out $dbname.$col.csv | |
done | |
IFS=$OIFS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment