我在路线中使用此代码:
MyModel.aggregate(
[
{ "$group": {
"_id": "$date",
"participants": { "$sum": "$participants" },
"peoples": { $sum: 1 }
}
},
],
function(err, result) {
console.log(result)
}
......etc......
这是聚合日期,参与者和人民,但我想访问名称字段,我尝试这样:
"_id": "$date",
"name": "$name",
"participants": { "$sum": "$participants" },
"peoples": { $sum: 1 }
但正在回归:
{ [MongoError: exception: the group aggregate field 'name' must be defined as an expression inside an object]
name: 'MongoError',
errmsg: 'exception: the group aggregate field \'some\' must be defined as an expression inside an object',
code: 15951,
ok: 0 }
我做错了什么?
答案 0 :(得分:1)
您需要$first
运算符。即:
MyModel.aggreagate(
[
{ "$group": {
"_id": "$date",
"name": { "$first": "$name" },
"participants": { "$sum": "$participants" },
"peoples": { "$sum": 1 }
},
],
function(err,results) {
// rest of processing.
}
);
怀疑你的"人民"和"参与者"字段也是错误的。但这是另一个在这里脱离背景的问题。