我想聚合2个字段,并希望以嵌套的方式完成gouping。我怎样才能做到这一点?目前,我按以下方式进行分组
var query = [
{ '$group': {
'_id': {
'employee': '$employee',
'sector': '$sector'
},
'bookCount': { '$sum': 1 }
}},
{ '$sort': { 'count': -1 } }
];
Order.aggregate(query, function(err, results){
res.json(results)
});我希望结果在形式上
{abc:{sector1:4, sector3:5}, xyz: {sector1:10, sector2:23}}其中,abc,xyz是雇员,sector1,sector2是部门。
如何聚合以获得嵌套结果?
我的原始文件是
[
{
"sector": "sector1",
"employee": "xyz"
},
{
"sector": "sector1",
"employee": "abc"
},
{
"sector": "sector1",
"employee": "abc"
},
{
"sector": "sector2",
"employee": "abc"
}
]我希望结果是形式上的
{abc:{sector1:2,sector2:2}, xyz: {sector1:1}}发布于 2015-01-15 12:27:36
您不能在聚合框架中使用“数据”作为“键名”,也不能使用嵌套属性创建嵌套对象。你也不应该这样做,因为这是一个“反模式”。数据就是数据,应该保持这种状态。此外,还有更好的方法来做到这一点:
Order.aggregate([
{ "$group": {
"_id": {
"employee": "$employee",
"sector": "$sector"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.employee",
"sectors": {
"$push": {
"sector": "$_id.sector",
"count": "$count"
}
}
}}
],function(err,docs) {
});它返回如下结构:
[
{
"_id" : "xyz",
"sectors" : [
{
"sector" : "sector1",
"count" : 1
}
]
},
{
"_id" : "abc",
"sectors" : [
{
"sector" : "sector2",
"count" : 1
},
{
"sector" : "sector1",
"count" : 2
}
]
}
]因此,您有一个用于"employee“值的主分组键,其他结果被”推送“到一个数组中。
这是一个更好的结构,在键的命名方面取得了一致的结果。
https://stackoverflow.com/questions/27961916
复制相似问题