我有三个 mongodb 集合。我想按日期、月份和年份对集合进行分组,然后按条件求和,以便在一个表中显示三个集合的总计。但是,我在生成 mongodb 聚合代码时遇到了问题。
收藏A
{
_id: "1",
"Name": "John",
"Booked": "Executive"
"date": 2023 - 03 - 02 T18: 15: 26.723 + 00: 00
}, {
_id: "2",
"Name": "Peter",
"Booked": "Economy",
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
}, {
_id: "3",
"Name": "Wade",
"Booked": "Economy",
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
},
收藏B
{
_id: "1",
"Name": "John",
"Amount": 200,
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
}, {
_id: "2",
"Name": "Peter",
"Amount": 300,
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
}, {
_id: "3",
"Name": "Wade",
"Amount": 100,
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
},
收藏C
{
_id: "3",
"Name": "Wade",
"Country": "USA",
"date": 2023 - 03 - 19 T19: 15: 26.723 + 00: 00
},
我希望能够按日期、月份和年份汇总经济舱预订总数,也能够按日期、月份和年份汇总客户的原籍国。
我怎样才能改进这段代码
collectionA.aggregate([
{$lookup:
{
from: "collectionB",
localField: "_id",
foreignField: "_id",
as: "collectionB"
}
},
{$unwind: "$collectionB"},
{$lookup:
{
from: "collectionC",
localField: "_id",
foreignField: "_id",
as: "collectionC"
}
},
{$unwind: "$collectionC"},
{
"$group": {
_id: {
year: {$year: "$date"},
month: {$month: "$date"},
dayOfMonth: {$dayOfMonth: "$date"},
},
"Economy": {
$sum: {
"$cond": [
{"$eq": ["$Booked", "Economy"]},
1,
0
]
}
},
"USA": {
$sum: {
"$cond": [
{"$eq": ["$Country", "USA"]},
1,
0
]
}
}
}
}
])
提前致谢