我想使用聚合和分组阶段对所有“总计”字段值求和。 我的代码和文档在这里
文件
{
"_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);
}
})
它给出“result []”日志。
最佳答案
我试过了,效果不错。看起来问题出在 from 和 to 上。在聚合 $match 管道中,我们需要与字段具有相同的类型。您需要 parseInt()
变量,因为我们从表达请求查询中获取字符串形式。
"$match": {
"updateDate": {
"$gte": parseInt(from), "$lte": parseInt(to)
}
}
关于node.js - 使用 $group stage 和 $sum 运算符聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38719285/