查询mongodb 结果后写入csv

import pymongo
import codecs
import csv

client = pymongo.MongoClient(‘ip‘,port)
db=client.admin
db.authenticate("user", "password", mechanism=‘SCRAM-SHA-1‘)


database = "databasename"
db = client[database]
collection = "collection_name"
db_coll = db[collection]
with codecs.open(‘d:\data18.csv‘,‘w‘,‘utf-8‘) as csvfile:
writer = csv.writer(csvfile)
#写入csv的字段,需要的继续后面添加
writer.writerow([‘user_id‘,‘work_unit‘,‘pe_date‘])
#writer.writerow([‘userId‘,‘group‘,‘batch‘,‘testId‘])


#后面的字典则是mongo中的字段名,需要筛选的字段
for d in db_coll.find({"pe_date": {"$regex": "2018"},"work_unit":"事业部"},{‘user_id‘:True,‘work_unit‘:True,‘pe_date‘:True}):
writer.writerows([[d[‘user_id‘],d[‘work_unit‘],d[‘pe_date‘]]])
#   for d in db_coll.find({"group":"事业部","batch":"2018"},{‘userId‘:True,‘group‘:True,‘batch‘:True,‘testId‘:True}):
# writer.writerows([[d[‘userId‘],d[‘group‘],d[‘batch‘],d[‘testId‘]]])



查询mongodb 结果后写入csv

上一篇:[开源] .Net 使用 ORM 访问 神舟通用数据库(神通)


下一篇:LocalReport Print with C# C#打印RDLC