多场Pymongo聚集

2024-09-28 21:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要通过两个字段获得文件总数:timestate

time是一个通过pymongo的datetime对象,我只能使用

'$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里面

^{pr2}$

它以{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.

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


Tags: 方法iddatetime格式countgroupyear
1条回答
网友
1楼 · 发布于 2024-09-28 21:31:44

您需要在您的$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 } 
}

相关问题 更多 >