Reputation: 49
I'm new to python.
what I have:
I am using mongoDb and 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.
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!
Upvotes: 0
Views: 373
Reputation: 1029
If you really want to use python:
dict0={}
if not 'date' in dict0.keys(): dict0['date']=[value]
else: dict0['date'].append(value)
Upvotes: 0
Reputation: 474271
Don't solve it on the python level, let mongodb group the records using aggregate()
:
pipe = [
{'$match': {'$timeout': False}},
{'$group': {'_id': '$created_time',
'comments': {'$push': '$comments'}}},
]
db.comments.aggregate(pipeline=pipe)
Upvotes: 4