Skip to content

Instantly share code, notes, and snippets.

@jasonwash
Created March 5, 2014 18:45
Show Gist options
  • Save jasonwash/9373846 to your computer and use it in GitHub Desktop.
Save jasonwash/9373846 to your computer and use it in GitHub Desktop.
Shell script to create a CSV file from a MongoDB collection. The CSV file will contain all possible top-level keys. Embedded documents are not handled.
#!/bin/bash
function usage {
printf "Usage:\n$0 <db_name> <collection_name> <output_csv_file>\n"
exit 1
}
db_name=$1
collection=$2
output_file=$3
[[ -z $collection ]] && usage
[[ -z $db_name ]] && usage
[[ -z $output_file ]] && usage
fields=$(mongo "$db_name" --quiet <<EOF | grep -e "_id,"
mr = db.runCommand({
"mapreduce" : "$collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "$collection" + "_keys"
});
var uniqueFields = db[mr.result].distinct("_id");
print(uniqueFields);
EOF
)
mongoexport --db "$db_name" --collection "$collection" --csv --fields "$fields" --out "$output_file"
printf "CSV contents exported to $output_file\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment