Hems Lodha Hems Lodha - 4 months ago 11
Node.js Question

aggregation with $group stage and $sum operator

I want to sum all "total" fields values using aggregation and group stage.
my code and documents is here

documents

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


I'm doing below query for fetch sum of "total" values

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);
}
})


Its giving "result []" log.

Max Max
Answer

I have try that, it is working. It looks like the issue is with from and to. In aggregation $match pipeline we need to have same type as field.You need parseInt() the variables as we get string form express request query.

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