数据类型:{'name':'tom','date':datetime.datetime(2017,7,1,11,35)}{'name':'tom','date':datetime.datetime(2017,7,1,12,25)}{'name':'tom','date':datetime.datetime(2017,7,3,13,32)}{'name':'bob','date':datetime.datetime(2017,7,1,15,37)}{'name':'bob','date':datetime.datetime(2017,7,2,9,15)}{'name':'sue','date':datetime.datetime(2017,7,1,17,15)}{'name':'sue','date':datetime.datetime(2017,7,2,12,25)}想要按照日期来进行聚合统计出每个人每天有几条记录,希望结果是这样的:{'date':'2017-7-1','name':['tom':1,'bob':1,'sue':1]}{'date':'2017-7-2','name':['bob':1,'sue':1]}{'date':'2017-7-3','name':['bob':1,'sue':1]}困惑了好几天了,按照日期来分组弄出来了,但是计数不晓得怎么弄db.coll.aggregate([{'$group':{'_id':{'$dateToString':{'format':'%Y-%m-%d','date':'$date'}}}}])这样把日期给分组了,但是对‘name’进行计数,却不晓得怎么弄谢谢楼下两位的回答,这样已经解决了问题。抱歉上面的格式错了,应该是这个{'date':'2017-7-1','name':{'tom':1,'bob':1,'sue':1}}我用的python,另外定义一个函数就可以转换过来了.格式从语言层面就可以解决了,s=[{"_id":"2017-08-03","name":[{"name":"tom","count":1}]},{"_id":"2017-08-01","name":[{"name":"sue","count":1},{"name":"bob","count":1},{"name":"tom","count":2}]},{"_id":"2017-08-02","name":[{"name":"sue","count":1},{"name":"bob","count":1}]}]defdb_dict(s):dicts=[]forlineins:res_dict={}forxinline.get('name'):names=x.get('name')values=x.get('count')res_dict[names]=valuesres=dict(dates=line.get('_id'),count=res_dict)dicts.append(res)returndicts函数执行完的结果就得到想要的格式了[{'dates':'2017-08-03','count':{'tom':1}},{'dates':'2017-08-01','count':{'tom':2,'bob':1,'sue':1}},{'dates':'2017-08-02','count':{'bob':1,'sue':1}}]
添加回答
举报
0/150
提交
取消