Skip to content

Instantly share code, notes, and snippets.

@nestoru
Last active February 18, 2021 00:06
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 nestoru/5e9e98492567100dc9c6a2156f95bcfc to your computer and use it in GitHub Desktop.
Save nestoru/5e9e98492567100dc9c6a2156f95bcfc to your computer and use it in GitHub Desktop.
mongo-collection-to-csv.sh
#!/bin/bash -e
# mongo-collection-to-csv.sh
#
# description: Exports all field from any mongodb collection to CSV
# author: Nestor Urquiza
# date: 20210218
# env vars
password=$MONGODB_PWD
# functions
function fail() {
echo "Usage:"
echo "export MONGODB_PWD=**** \\"
echo "mongo-collection-to-csv.sh authdb user collection csvpath host"
echo
echo "Example:"
echo "export MONGODB_PWD=mypwd && ./mongo-collection-to-csv.sh admin mydb myuser mycollection /tmp/mycollection.csv 'cluster0-shard-00-00-10xyz.mymongo.net:27017,cluster0-shard-00-01-10xyz.mymongo.sample.com:27017,cluster0-shard-00-02-10xyz.mymongo.sample.com:27017'"
exit 1
}
function run() {
OIFS=$IFS;
IFS=",";
echo 'exporting collection' ${collection} to ${csvpath}
keys=`mongo "$host/$db" --ssl --authenticationDatabase $authdb -u $user -p"$password" --eval "rs.slaveOk(); var keys = []; for(var key in db.${collection}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys.join(',');" --quiet`;
mongoexport --db=lms --collection=${collection} --type=csv --out=$csvpath -h "'$host'" -u $user -p"$password" --ssl --authenticationDatabase=admin --fields "'$keys'"
IFS=$OIFS;
}
# main
# arguments
authdb=$1
db=$2
user=$3
collection=$4
csvpath=$5
host=$6
if [ "$MONGODB_PWD" == "" ] || [ "$authdb" == "" ] || [ "$db" == "" ] || [ "$user" == "" ] || [ "$collection" == "" ] || [ "$csvpath" == "" ] || [ "$host" == "" ]; then
fail
else
run
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment