gpt4 book ai didi

javascript - 如何在 Mongodb 的 $push 部分中对一个组进行分组

转载 作者:行者123 更新时间:2023-11-30 13:45:05 24 4
gpt4 key购买 nike

假设我们有代码:

EightWeekGamePlan.aggregate(
[
{ $sort: { Week: 1 } },
{
$group: {
_id: {
LeadId: "$LeadId",
BusinessName: "$BusinessName",
PhoneNumberMasque: "$PhoneNumberMasque",
City: "$City",
Rooms: "$Rooms"
// dateToString: { format: "%Y-%m-%d", date: "$InserDate" }
},
Weeks: {
$push: {
Week: "$Week",
Status: "$Status",
InsertDate: "$InsertDate",
TargetClient: "$TargetedToBeClaimedByClientType",
MaxClaims: "$TotalClaimsToBeClaimedByClientType",
CurrentClaims: "$TotalClaimsLeftToBeClaimedByClientType"
}
}
}
}
]

我将然后 $pushing 分组到一个数组中,但是在将数据传回客户端之前需要另一组:我们如何分组 WeeksWeek 排列?

请不要使用另一个分组 $Week在第一个$group .

当前答案的示例(在第二组之前),我想将其按周再次分组:

LeadId: "6823f5c6-244e-41aa-89eb-5d4d87fac068"
PhoneNumberMasque: "076-5465743856475"
BusinessName: "Something ... "
City: "Somewhere ..."
Rooms: 2
Weeks: Array(10): Array(10)
0: {Week: 1, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 1, MaxClaims: 1, …}
1: {Week: 1, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 2, MaxClaims: 2, …}
2: {Week: 1, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 3, MaxClaims: 2, …}
3: {Week: 2, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 2, MaxClaims: 5, …}
4: {Week: 3, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 3, MaxClaims: 5, …}
5: {Week: 4, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 4, MaxClaims: 5, …}
6: {Week: 5, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 5, MaxClaims: 5, …}
7: {Week: 6, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 6, MaxClaims: 5, …}
8: {Week: 7, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 7, MaxClaims: 5, …}
9: {Week: 8, Status: 1, InsertDate: "2019-12-27T08:44:26.000Z", TargetClient: 8, MaxClaims: 5, …}

最佳答案

如果您不想使用额外的 $group 阶段,您可以利用 $reduce结合 $filter . $setUntion为您提供一组独特的 Week 数字,然后使用 $filter 您可以将匹配的文档从 Weeks 数组带入您的结果集中,使用组合子文档$concatArrays :

db.collection.aggregate([
{
$project: {
Weeks: {
$reduce: {
input: { $setUnion: "$Weeks.Week" },
initialValue: [],
in: {
$concatArrays: [
"$$value",
[{
WeekNum: "$$this",
Docs: { $filter: { input: "$Weeks", as: "w", cond: { $eq: [ "$$w.Week", "$$this" ] } } }
}]
]
}
}
}
}
}
])

Mongo Playground

关于javascript - 如何在 Mongodb 的 $push 部分中对一个组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59497609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com