我试图在我的猫鼬上使用聚合。
理想的脚本,将总结过去100天内的所有crime.amount和heavy_crime数量,并且仅获得与用户标识相关的结果。
(今天:todate
)
(100天前:fromdate
)
模型:
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}
},
尝试代码:
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))
}
那么如何使用正确的用户ID来使聚合仅用于过去100天的工作?
numberO Would ideally return number of crime and heavycrime the last 100 days.
答案 0 :(得分:1)
您错过了$match
阶段。
将您的日期比较移至匹配阶段,然后将$group
移至犯罪行为。
dailyStats.aggregate([
{
"$match": {
"user": userid,
"time": {
"$gte": fromdate.getTime(),
"$lte": todate.getTime()
}
}
},
{
"$group": {
"_id": null,
"total": {
"$sum": {
"$add": [
"$crime.amount",
"$heavycrime.amount"
]
}
}
}
}
]);