Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export all MongoDB collections as csv without specifying fields (tested only on non-empty collections with plain scheme).
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
You can’t perform that action at this time.