[英]Python - pymongo list inside dict
I'm new to python. 我是python的新手。
what I have: 我有的:
I am using mongoDb and python. 我正在使用mongoDb和python。 Using distinct dates, I want to retrieve all comments from that date. 使用不同的日期,我想检索该日期的所有评论。
example datebase: 日期库示例:
id|created_time|comment |.....
0 |2014-01-01 | hi! |......
1 |2014-02-01 | hello! |......
2 |2014-01-01 | bye |......`
what I tried: 我试过的
text = db.comments.find(timeout=False)
time = db.comments.distinct('created_time')
#some code
#get all distinct date and put into list
timeArray = []
for allTime in time:
timeArray.append(allTime)
comDict = {}
for allCom in text:
global comDict
if(allCom['created_time'] == timeArray[1]):
#note i'm used timeArray[1] to test the code.
comDict.update({allCom['created_time']:allCom['comments']})
print comDict
dict cannot have duplicated keys, therefore the .update
keep changing the value instead of appending it but i don't know of other way. dict不能有重复的键,因此.update
不断更改值而不是附加值,但我不知道其他方法。
what I need: 我需要的:
{2014-01-01:['hi','bye'], 2014-02-01:['Hello!']}
I hope to get the above result but I am not sure how to do that. 我希望得到上述结果,但是我不确定该怎么做。 Can someone enlighten me as to what I should do, or what I did wrong? 有人能启发我应该做什么或做错了什么吗?
Thanks in advance! 提前致谢!
Don't solve it on the python level, let mongodb group the records using aggregate()
: 不要在python级别上解决它,让mongodb使用aggregate()
对记录进行分组:
pipe = [
{'$match': {'$timeout': False}},
{'$group': {'_id': '$created_time',
'comments': {'$push': '$comments'}}},
]
db.comments.aggregate(pipeline=pipe)
If you really want to use python: 如果您真的想使用python:
dict0={}
if not 'date' in dict0.keys(): dict0['date']=[value]
else: dict0['date'].append(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.