Last active
December 19, 2015 23:09
-
-
Save nopolabs/6033172 to your computer and use it in GitHub Desktop.
javascript csvBuilder to output results of mongo query as csv
This file contains 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
// 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