【问题标题】:Pymongo Aggregation with multi-fields [duplicate]具有多字段的 Pymongo 聚合 [重复]
【发布时间】:2016-04-01 01:47:26
【问题描述】:

我正在尝试使用 Pymongo 对多个字段进行聚合,但我还没有找到获得正确值的方法。

我需要通过 2 个字段获取文件总数:timestate

time 是通过 pymongo 的日期时间对象,我只能使用 yy/mm/dd 获取

'$group': { "_id":{
            "date":{"$concat": [
                   {"$substr": [{"$year": "$date"}, 0, 4 ]},
                   "-",
                   {"$substr": [{"$month": "$date"}, 0, 2 ]},
                   "-",
                   {"$substr": [{"$dayOfMonth": "$date"}, 0, 2 ]},
              ]}},
             "count":{"$sum": 1}}

这可以为我提取正确的日期并计算日志的数量,但现在我还需要按state 分组,所以它在 mysql 中变为GROUP BY date, state

我尝试将其添加到_id

'$group': { "_id":{
            "date":{"$concat": [
                   {"$substr": [{"$year": "$date"}, 0, 4 ]},
                   "-",
                   {"$substr": [{"$month": "$date"}, 0, 2 ]},
                   "-",
                   {"$substr": [{"$dayOfMonth": "$date"}, 0, 2 ]},
              ]}},
             "_id":{"state":"$timeline.state"},
             "count":{"$sum": 1}}

它以{u'count': 4111, u'_id': {u'state': [0, 1]}} 等格式创建多个输出,0 和1 是不同状态的代码。找不到日期。

然后我尝试了

'$group': { "_id":{
            "date":{"$concat": [
                   {"$substr": [{"$year": "$date"}, 0, 4 ]},
                   "-",
                   {"$substr": [{"$month": "$date"}, 0, 2 ]},
                   "-",
                   {"$substr": [{"$dayOfMonth": "$date"}, 0, 2 ]},
              ]}},
             "state":"$timeline.state"},
             "count":{"$sum": 1}}

我得到了failed: A pipeline stage specification object must contain exactly one field.

这看起来像我没有在正确的位置得到括号,但无论我如何更改格式,同样的错误仍然存​​在。现在我想知道这是否真的是支架的问题。最重要的是,我该如何正确地做到这一点?

【问题讨论】:

    标签: python mongodb pymongo aggregation-framework


    【解决方案1】:

    您需要在 $group 阶段中​​使用复合 _id 字段,如下所示:

    "$group": { 
        "_id":{
            "date":{
                "$concat": [
                    { "$substr": [ { "$year": "$date" }, 0, 4 ] }, 
                    "-", 
                    { "$substr": [ { "$month": "$date" }, 0, 2 ] },
                    "-",
                    { "$substr": [ { "$dayOfMonth": "$date" }, 0, 2 ] }
                ] 
            }, 
            "state": "$timeline.state" 
        },
        "count": { "$sum": 1 } 
    }
    

    【讨论】:

    • 我明白了。所以一切都必须在_id 括号内。我想我现在可以开始工作了。只有一个count 就可以了,对吧?我不需要以某种方式先数date,然后再数state
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2020-12-08
    • 2019-08-20
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多