聚合比较 mongodb 中的两个数组?
aggregate compare two array in mongodb?
我有以下查询结果。
[
{
"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,
"totalUserCount": 4,
"userCountPerDay": [
{
"createdAt": "2021-05-27",
"userCount": 0
},
{
"createdAt": "2021-05-28",
"userCount": 2
},
{
"createdAt": "2021-05-29",
"userCount": 0
},
{
"createdAt": "2021-05-30",
"userCount": 0
},
{
"createdAt": "2021-05-31",
"userCount": 0
},
{
"createdAt": "2021-06-01",
"userCount": 1
},
{
"createdAt": "2021-06-02",
"userCount": 1
}
]
}
]
谢谢
$project
显示必填字段
$map
迭代 dayRange
数组 的循环
$cond
检查当前日期是否在 userCountPerDay.createdAt
数组中,
- 是,
$indexOfArray
获取数组索引或 userCountPerDay
数组中的当前日期,$arrayElemAt
从 returned 索引[=31 获取 element/object =]
- 无,return
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
}
]
}
}
}
}
}
])
我有以下查询结果。
[
{
"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,
"totalUserCount": 4,
"userCountPerDay": [
{
"createdAt": "2021-05-27",
"userCount": 0
},
{
"createdAt": "2021-05-28",
"userCount": 2
},
{
"createdAt": "2021-05-29",
"userCount": 0
},
{
"createdAt": "2021-05-30",
"userCount": 0
},
{
"createdAt": "2021-05-31",
"userCount": 0
},
{
"createdAt": "2021-06-01",
"userCount": 1
},
{
"createdAt": "2021-06-02",
"userCount": 1
}
]
}
]
谢谢
$project
显示必填字段$map
迭代dayRange
数组 的循环
$cond
检查当前日期是否在userCountPerDay.createdAt
数组中,- 是,
$indexOfArray
获取数组索引或userCountPerDay
数组中的当前日期,$arrayElemAt
从 returned 索引[=31 获取 element/object =] - 无,return
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
}
]
}
}
}
}
}
])