I have over 100 fields and I am looking for a way so that I can just export the entire collection as CSV format
The command-line is asking to provide all fields via
-f [ --fields ] arg comma seperated list of field names e.g. -f name,age
Thank you
In bash you can create this "export-all-collections-to-csv.sh" and pass the database name as the only argument (feel free to reduce this to a single collection):
OIFS=$IFS;
IFS=",";
dbname=$1 #put "database name" here if you don't want to pass it as an argument
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();" --quiet`;
collectionArray=($collections);
for ((i=0; i<${#collectionArray[@]}; ++i));
do
keys=`mongo $dbname --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.findOne()) { keys.push(key); }; keys;" --quiet`;
mongoexport --db $dbname --collection ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done
IFS=$OIFS;
You could create a file with the field names (may be easier for you):
--fieldFile arg file with fields names - 1 per line
In your case they might all be the same but the reason you have to specify the field names is because they could be different for every document however the field names in the csv must be fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With