Skip to content

Instantly share code, notes, and snippets.

@sujith3g
Created February 11, 2016 09:16
Show Gist options
  • Save sujith3g/06d7faf66a2e17553e9b to your computer and use it in GitHub Desktop.
Save sujith3g/06d7faf66a2e17553e9b to your computer and use it in GitHub Desktop.
// mongo export to csv
// Usage "$ mongo localhost:27017/my_db script.js > test.csv "
cursor = db.collection.find();
var fields = [
"field1",
"field2",
"field3",
"field4",
"created_field"
];
print(fields.join(","));
while ( cursor.hasNext() ) {
row= cursor.next();
row.created_field = row.list ? row.list.reduce(function(prev, cur){
return prev + (cur.doc_code === "ABCD" ? 1: 0);
},0): 0;
var csv_row = "";
fields.forEach(function(col, index){
if(index < (fields.length-1)){
csv_row += "\"" + (row[col] ? row[col] : "") + "\t\",";
}else{
csv_row += "\"" + (row[col] ? row[col] : "") + "\t\"";
}
});
print(csv_row);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment