secret
Created

Convert results of a aggregate framework to CSV (http://stackoverflow.com/questions/12208771)

  • Download Gist
agg-to-csv.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#!/usr/bin/env python
 
import csv
 
def quoteStrings(strArr):
 
return ["'%s'"%k for k in strArr]
 
result = [
{'_id': 'Rob', 'x': [12], 'y': [2], 'z': []},
{'_id': 'George', 'x': [5], 'y': [3], 'z': [9]}
]
 
# open file and create csv writer
f = open('out.csv', 'w')
writer = csv.writer(f)
 
# flatten sub-arrays to double-quoted comma-separated strings, e.g. [1, 2, 3] ==> "1, 2, 3"
 
for i, row in enumerate(result):
for key in row:
if isinstance(row[key], list):
result[i][key] = ','.join([str(x) for x in row[key]])
 
# write keys to csv
keys = [k for k in result[0].keys() if k!='_id']
writer.writerow(quoteStrings(['Name'] + keys))
 
for row in result:
writer.writerow(quoteStrings([row[k] for k in ['_id'] + keys]))
 
f.close()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.