我正在尝试使用带有多个字段的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
因此它会出现GROUP BY date, state
在mysql中
我尝试将其添加到里面 _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.
看来我没有将括号放在正确的位置,但是无论我如何更改格式,都将出现相同的错误。现在我想知道这是否真的是括号的问题。最重要的是,我该如何正确执行?
您需要_id
在$group
阶段中使用复合字段,如下所示:
"$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 }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句