【发布时间】:2022-11-23 00:57:15
【问题描述】:
所以这是我的收藏。这包括用户及其数据
{
userId: 6udg,
data: [
{
date: 22-09-2022
hits: 98
},
{
date: 23-09-2022
hits: 88
},
{
date: 24-09-2022
hits: 100
},
{
date: 24-11-2022
hits: 145
},
{
date: 25-11-2022
hits: 75
}
]
},
{
userId: 7tu5,
data: [
{
date: 22-09-2022
hits: 98
},
{
date: 23-09-2022
hits: 88
},
{
date: 24-09-2022
hits: 100
},
{
date: 24-11-2022
hits: 18
},
{
date: 25-11-2022
hits: 65
}
]
}
以下是我如何使用按周、月和年过滤的命中对象创建聚合。首先,我匹配要获取其数据的用户。然后我使用投影来获取我想要的自定义字段。
Users.aggregate([
{
$match: {
userId: req.params.userId
}
},
{
$project: {
_id: 0,
last_seven_days: {
$filter: {
input: "$data",
as: "index",
cond: {
$and: [
{
$gte: [
"$$index.date",
new Date(moment().utc().startOf("week"))
]
},
{
$lte: [
"$$index.date",
new Date(moment().utc().endOf("week"))
]
}
]
}
},
},
last_month: {
$filter: {
input: "$data",
as: "index",
cond: {
$and: [
{
$gte: [
"$$index.date",
new Date(moment().utc().startOf("month"))
]
},
{
$lte: [
"$$index.date",
new Date(moment().utc().endOf("month"))
]
}
]
}
}
},
last_year: {
$filter: {
input: "$data",
as: "index",
cond: {
$and: [
{
$gte: [
"$$index.date",
new Date(moment().utc().startOf("year"))
]
},
{
$lte: [
"$$index.date",
new Date(moment().utc().endOf("month"))
]
}
]
}
}
}
}
}
])
我想要做的是在每个中添加一个名为“平均”的键最后七天,上个月, 和去年- 分别包含周、月和年的平均点击率
预期输出:
{
userId: 6udg
last_seven_day:[
avg: <avg>
data:[
{
date: 24-11-2022,
hits: 145,
},
{
date: 25-11-2022,
hits: 75,
}
]
]
}
【问题讨论】:
-
查看$reduce,我认为它会满足您的需求
-
请发布有效的 json 文档以获取示例数据和预期输出。
-
@ray 请检查我编辑的问题