Last active
September 7, 2019 16:30
-
-
Save dkendrick/ccdebfaa02586a1bdf96fcaeee535b9d to your computer and use it in GitHub Desktop.
Print mongo result to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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 | |
}; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Print mongo result to CSV
Run this script on the mongo instance to install and use the following syntax to print a CSV result