Skip to content

Instantly share code, notes, and snippets.

@milkyklim
Forked from mderazon/mongo-dump-csv.sh
Last active June 19, 2019 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milkyklim/d0e84b0546316b6ceed1327e9801e834 to your computer and use it in GitHub Desktop.
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).
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