Reputation: 159
Im trying to use aggregation on my mongoose .
The ideal script, would sum up all crime.amount and heavy_crime amount the last 100 days, and only get the results relevant with the userid.
(today: todate
)
( 100 days ago: fromdate
)
model:
time: Number,
userid : String,
crime: {
cash: {type: Number, default: 0},
amount: { type: Number, default: 0}
},
heavy_crime: {
cash: {type: Number, default: 0},
amount: { type: Number, default: 0}
},
Attempting code:
function checkCrimeRating(userid) {
var todate = new Date();
var fromdate = new Date();
var lastfive = new Date();
var MainDate = date.getDate();
fromdate.setHours(0,0,0,0);
todate.setHours(0,0,0,0);
lastfive.setHours(0,0,0,0);
lastfive.setDate(MainDate - 5);
fromdate.setDate(MainDate - 100);
return dailyStats.aggregate(
{ $group: {
_id: "$time" : $gte {fromdate.getTime()}, $lte: {todate.getTime()},
total: { $sum: { $add: ["$crime.amount", "$heavycrime.amount"] } },
}}
).then(function (numberO))
}
So how can i make the aggregation only work sum up the last 100 days, with the right userid?
numberO Would ideally return number of crime and heavycrime the last 100 days.
Upvotes: 0
Views: 775
Reputation: 75914
You are missing the $match
stage.
Move your date comparison to match stage followed by $group
to sum crimes.
dailyStats.aggregate([
{
"$match": {
"user": userid,
"time": {
"$gte": fromdate.getTime(),
"$lte": todate.getTime()
}
}
},
{
"$group": {
"_id": null,
"total": {
"$sum": {
"$add": [
"$crime.amount",
"$heavycrime.amount"
]
}
}
}
}
]);
Upvotes: 1