使用$ group阶段和$ sum运算符进行聚合

我想使用聚合和小组阶段来总和所有“总计”字段值。 我的代码和文件在这里

文件

{ "_id": "57a068477b2l51ec16eb7das", "userID":"5742c6eedsaadsd93573e", "profileID":"5742aee49adv520593573c", "date": 1470130247779, "updateDate": 1470130361342, "total": 2 } { "_id": "57a068477b2l51ec16eb983", "userID":"5742c6eedsaadsd93573e", "profileID":"5742aee49adv520593573c", "date": 1470130247779, "updateDate": 1470130361342, "total": 1 } 

我正在做下面的查询获取“总”值的总和

  RecallProfile.aggregate([ { "$match": { "updateDate": { "$gte": from, "$lte": to } } }, { $group: { "_id": "$updateDate", "totalRecord": {"$sum": "$total"} } } ], function (err, result) { if (err) { console.log('error ', err); res.sendStatus(500); } else { console.log("result", result); res.sendStatus(200); } }) 

它给出“结果[]”日志。

我已经尝试过,它正在工作。 看起来问题是从和到。 在聚合$匹配pipe道中,我们需要和field有相同的types。你需要parseInt()这个variables来获得stringforms的expression请求查询。

 "$match": { "updateDate": { "$gte": parseInt(from), "$lte": parseInt(to) } }