Mongo: export all field data from a collection without specifying fields?

  • I have over 100 fields, and I'm looking for a way so that I can simply export the entire collection in CSV format

  • The command line asks to provide all fields through

-f [--fields] arg comma separates the list of field names, for example. -f name, age

  • Is there a way to get the whole collection, for example, using a dump, but not in bson format?
  • I need CSV data

thank

+5
source share
2 answers

You can create a file with field names (it might be easier for you):

--fieldFile arg         file with fields names - 1 per line

In your case, they can be the same, but the reason you must specify the field names is because they can be different for each document, however the field names in csv must be fixed.

0

bash "export-all-collections-to-csv.sh" ( ):

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;
+10

All Articles