MongoDB聚合查询,登录平均值


let pipeline = [{
$match: {
time: { $gt: 980985600 },
user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
}
},
{
$project: {
newDate: { '$toDate': "$time" },
user_id: '$user_id'
}
},
{
$group: {
_id: { week: { $week: "$newDate" }, year: { $year: "$newDate" }},
count: { $sum: 1 }
}
}]

我目前正试图通过mongoose执行聚合,以找到特定用户每周的平均登录次数。到目前为止,我已经能够得到每周的登录总数,但我很好奇是否有一种方法可以找到同一函数中这些最终分组的平均值。我该怎么做呢?

只需在查询中添加最后一个阶段:

{
$group: {
_id: null,
avg: { $avg: "$count" }
}
}

那么试试这个:

let pipeline = [
{
$match: {
time: { $gt: 980985600 },
user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
}
},
{
$project: {
newDate: { '$toDate': "$time" },
user_id: '$user_id'
}
},
{
$group: {
_id: { week: { $week: "$newDate" }, year: { $year: "$newDate" } },
count: { $sum: 1 }
}
},
{
$group: {
_id: null,
avg: { $avg: "$count" }
}
}
];

最新更新