我如何使用 mongoose 聚合推送特定字段的值

How can i push values of a specific field with mongoose aggregate

我在路由中使用此代码:

    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 }

我做错了什么?

为此您需要 $first 运算符。即:

MyModel.aggreagate(
    [
        { "$group": {
            "_id": "$date",
            "name": { "$first": "$name" },
            "participants": { "$sum": "$participants" }, 
            "peoples": { "$sum": 1 }
        },
    ],
    function(err,results) { 
        // rest of processing.
    }
);

怀疑你的"peoples"和"participants"字段也有误。但这是另一个脱离上下文的问题。