问题描述
[
{
"dayCount": 3,"dayRange": [
"2021-05-27","2021-05-28","2021-05-29","2021-05-30","2021-05-31","2021-06-01","2021-06-02"
],"totalUserCount": 4,"userCountPerDay": [
{
"createdAt": "2021-05-28","userCount": 2
},{
"createdAt": "2021-06-02","userCount": 1
},{
"createdAt": "2021-06-01","userCount": 1
}
]
}
]
这是按日期划分的用户访问量。
我需要比较“dayRange”和“userCountPerDay.createdAt”
对于“userCountPerDay.createdAt”中不存在的日期,将“userCount”设置为0
我想使用 mongo 聚合来跟踪结果
请帮帮我。
[
{
"dayCount": 3,"userCountPerDay": [
{
"createdAt": "2021-05-27","userCount": 0
},{
"createdAt": "2021-05-28",{
"createdAt": "2021-05-29",{
"createdAt": "2021-05-30",{
"createdAt": "2021-05-31","userCount": 1
}
]
}
]
谢谢
解决方法
-
$project
显示必填字段 -
$map
迭代dayRange
数组的循环 -
$cond
检查当前日期是否在userCountPerDay.createdAt
数组中的条件,- 是的,
$indexOfArray
用于在userCountPerDay
数组中获取数组索引或当前日期,$arrayElemAt
从返回的索引中获取元素/对象 - 不,返回
createdAt
和userCount
字段
- 是的,
db.collection.aggregate([
{
$project: {
dayCount: 1,totalUserCount: 1,userCountPerDay: {
$map: {
input: "$dayRange",in: {
$cond: [
{ $in: ["$$this","$userCountPerDay.createdAt"] },{
$arrayElemAt: [
"$userCountPerDay",{ $indexOfArray: ["$userCountPerDay.createdAt","$$this"] }
]
},{
createdAt: "$$this",userCount: 0
}
]
}
}
}
}
}
])