如何使用pymongo将mongo数据导出到csv?

时间:2017-01-08 14:45:57

标签: mongodb pymongo export-to-csv

我的代码:

data = db.get_collection('activity_tracker').find({"companyId" : "527d4b23-347a-4ad2-81d8-dfd66af5631a", 'userEmail':{'$ne':'abc@xyz.in'}})

with open('asdxk.csv', 'w') as outfile:

    fields = ['companyId', 'userEmail']
    writer = csv.writer(outfile, fields)
    for post in data:
        writer.writerow([post])

问题陈述:

使用上面的代码我将数据导出为CSV文件作为垃圾,但我想要做的是companyID和userEmail详细信息应该导出为csv作为行和列格式。标题名称应为companyID和userEmail。

1 个答案:

答案 0 :(得分:0)

使用 mongoexport 实用程序将数据导出到csv:

mongoexport -h localhost -d test -c activity_tracker --type=csv
--fields companyId,userEmail 
--q '{"companyId":"527d4b23-347a-4ad2-81d8-dfd66af5631a","userEmail":{"$ne":"abc@xyz.in"}}' 
--out asdxk.csv