【发布时间】:2016-04-01 01:47:26
【问题描述】:
我正在尝试使用 Pymongo 对多个字段进行聚合,但我还没有找到获得正确值的方法。
我需要通过 2 个字段获取文件总数:time 和 state
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