【问题标题】:Python - pymongo list inside dictPython - 字典中的 pymongo 列表
【发布时间】:2015-03-06 16:53:11
【问题描述】:

我是 python 新手。

我有什么:

我正在使用 mongoDb 和 python。使用不同的日期,我想从该日期检索所有 cmets。

示例数据库:

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 comDict

dict 不能有重复的键,因此 .update 不断更改值而不是附加它,但我不知道其他方式。

我需要什么:

{2014-01-01:['hi','bye'], 2014-02-01:['Hello!']}

我希望得到上述结果,但我不知道该怎么做。有人能告诉我我应该做什么,或者我做错了什么吗?

提前致谢!

【问题讨论】:

    标签: python mongodb dictionary pymongo database


    【解决方案1】:

    不要在python层面解决,让mongodb使用aggregate()对记录进行分组:

    pipe = [
        {'$match': {'$timeout': False}},
        {'$group': {'_id': '$created_time', 
                    'comments': {'$push': '$comments'}}},
    ]
    db.comments.aggregate(pipeline=pipe)
    

    【讨论】:

      【解决方案2】:

      如果你真的想用python:

      dict0={}
      if not 'date' in dict0.keys(): dict0['date']=[value]
      else: dict0['date'].append(value) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-15
        • 2021-10-23
        • 1970-01-01
        • 2014-10-15
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        相关资源
        最近更新 更多