Skip to content

Instantly share code, notes, and snippets.

@dkendrick
Last active September 7, 2019 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkendrick/ccdebfaa02586a1bdf96fcaeee535b9d to your computer and use it in GitHub Desktop.
Save dkendrick/ccdebfaa02586a1bdf96fcaeee535b9d to your computer and use it in GitHub Desktop.
Print mongo result to CSV
/*globals db*/
db.system.js.save({
_id : 'CSVPrinter',
value : function CSVPrinter() {
var firstRun = true;
function checkFirstRun(record){
if (firstRun) {
firstRun = false;
printCSVHeader(record);
}
}
function csvSafeValue(candidate)
{
candidate = candidate || '';
var escapedSpaces = candidate
.toString()
.replace(/"/, '\"');
var result = '"' + escapedSpaces + '"';
return result;
}
function printCSVHeader(record) {
var properties = [];
for (var property in record) {
if (record.hasOwnProperty(property)) {
var value = csvSafeValue(property);
properties.push(value);
}
}
print(properties.join(','));
}
function getStringValue(property) {
property = property || '';
if (property instanceof Date) {
var day = property.getDate();
var month = property.getMonth() + 1;
var year = property.getFullYear();
return day + '/' + month + '/' + year;
}
return property.toString();
}
function printToCSV(record) {
var properties = [];
checkFirstRun(record);
for (var property in record) {
if (record.hasOwnProperty(property)) {
var value = getStringValue(record[property]);
var safeValue = csvSafeValue(value);
properties.push(safeValue);
}
}
print(properties.join(','));
}
return {
print : printToCSV
};
}
});
@dkendrick
Copy link
Author

Print mongo result to CSV

Run this script on the mongo instance to install and use the following syntax to print a CSV result

db.loadServerScripts();
var csvPrinter = new CSVPrinter();
db.collection.find({}).forEach(csvPrinter.print);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment