我如何总结我的mongodb集合中的值?

我有一个mongoose模型,看起来类似于这样的:

 var TestSchema = new Schema({ test_username: {type: String, required: true}, test_content: {type: String}, reactions: [{ test_username: {type: String, required: true}, value: {type: Number, required: true}, sent_at: {type: Date, required: true, default: Date.now} }], created_at: {type: Date, default: Date.now}, updated_at: {type: Date, default: Date.now} }) 

它存储我的Test对象有很多反应。 每个反应包含1-1 value和不同的用户名。 现在我正在尝试创build一个端点来获取Test id作为input,并返回它包含的所有反应的总和。

我开始写它:

 testRoutes.get('/:id/reactions/', functions.validateRequestsGET, function(req, res){ var testId = req.params.id; var query = Test... //here I'm stuck query.exec(function(err, reactions){ if(err) { res.send(err); return; } res.json(reactions); }); }); 

你能给我提示如何创build一个查询,可以返回一个JSON的总金额? 像{reactions: 17}或类似的东西?

尝试这个:

 Test.aggregate( { $match: { _id: testId // you might want to convert this from string to ObjectId() }}, { $project: { sumReactions: { $sum: "$reactions.value" } }} ) 

看一下在文档中的组累加器$组 ,也是很好的例子。