Skip to content

Instantly share code, notes, and snippets.

@nopolabs
Last active December 19, 2015 23:09
Show Gist options
  • Save nopolabs/6033172 to your computer and use it in GitHub Desktop.
Save nopolabs/6033172 to your computer and use it in GitHub Desktop.
javascript csvBuilder to output results of mongo query as csv
// Usage: mongo localhost:27017/test csvBuilder_example.js | awk 'NR > 3 { print }' > products.out
var c = db.products.find({}, { _id: 1, name: 1, type: 1, shipper: 1 });
function printCsv(c) {
while (c.hasNext()) {
var r = c.next();
print(csvBuilder().
add(r._id).
add(r.name).
add(r.type).
add(r.shipper['$id']).
build());
}
}
function csvBuilder() {
var data = '',
builder = {
add: function(field) {
if (data.length > 0) data += ',';
data += '"';
if (field === null || field === undefined) {
data += '';
} else if (typeof field == 'string' || field instanceof String) {
data += field.replace(/"/g, '""');
} else {
data += field;
}
data += '"';
return builder;
},
build: function() {
return data;
}
};
return builder;
}
print('p_id,p_name,p_type,p_shipper_id');
printCsv(c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment