我正在尝试使用相同的事件名称对所有字段进行分组,并对这些字段的参与者求和。
{
"_id": {
"$oid": "54b6ae8aec17b5e905a5813a"
},
"person": {
"name": "Something",
"phone": "(011) 9468-1319",
"email": "myemail@gmail.com",
"obs": ""
},
"event": {
"full": "20/11/01 Classic",
"date": "20/11/01",
"name": "Special",
"participants": 10
},
"__v": 0
}
{
"_id": {
"$oid": "54b6aeaad7e410ec05dd1ca2"
},
"person": {
"name": "Something",
"phone": "(011) 9468-1319",
"email": "myemail@gmail.com",
"obs": ""
},
"event": {
"full": "20/11/01 Classic",
"date": "20/11/01",
"name": "Special",
"participants": 10
},
"__v": 0
}
我只有这两个集合,我将以下代码用于event.full的一个组,并将它们与参与者(数字)字段相加。
这是代码:
MyModel.aggregate(
[
{ "$group":
{
_id: "$event.full",
participants: { "$sum": "$participants" },
count: { $sum: 1 }
}
},
{ "$skip": ( page-1 ) * 15 },
{ "$limit": 15 }
],
function(err, obj) {
res.send(obj);
}
);
这将返回以下对象:
[
{
_id: "20/11/01 Classic",
participants: 0,
count: 2
}
]
为什么sum字段不起作用?如何解决?
答案 0 :(得分:2)
你错过了event
使用它:
[
{ "$group":
{
_id: "$event.full",
participants: { "$sum": "$event.participants" },
count: { $sum: 1 }
}
},
{ "$skip": ( page-1 ) * 15 },
{ "$limit": 15 }
]