我对蟒蛇很陌生。
我拥有的:
我正在使用mongoDb和python。使用不同的日期,我想检索该日期的所有注释。
示例数据库:
id|created_time|comment |.....
0 |2014-01-01 | hi! |......
1 |2014-02-01 | hello! |......
2 |2014-01-01 | bye |......`我尝试了什么:
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 comDictdict不能有重复的键,因此.update不断地更改值,而不是追加它,但我不知道其他方法。
我需要什么:
{2014-01-01:['hi','bye'], 2014-02-01:['Hello!']}我希望得到上述结果,但我不知道该如何做。有人能告诉我我应该做什么,或者我做错了什么吗?
提前感谢!
发布于 2015-01-08 14:30:48
不要在python级别上解决它,让mongodb使用aggregate()对记录进行分组
pipe = [
{'$match': {'$timeout': False}},
{'$group': {'_id': '$created_time',
'comments': {'$push': '$comments'}}},
]
db.comments.aggregate(pipeline=pipe)发布于 2015-01-08 14:37:25
如果您真的想使用python:
dict0={}
if not 'date' in dict0.keys(): dict0['date']=[value]
else: dict0['date'].append(value) https://stackoverflow.com/questions/27842428
复制相似问题