gpt4 book ai didi

javascript - Mongoose 按数组最后一个对象中的属性分组

转载 作者:行者123 更新时间:2023-11-30 19:00:45 25 4
gpt4 key购买 nike

我有以下数据:

[
{
name: "Alert 1",
followusp: [
{
status: "new",
date: "now"
},
{
status: "do_it",
date: "now"
}
]
},
{
name: "Alert 2",
followusp: [
{
status: "new",
date: "now"
}
]
},
{
name: "Alert 3",
followusp: [
{
status: "new",
date: "now"
},
{
status: "engaged",
date: "now"
},
{
status: "canceled",
date: "now"
}
]
},
{
name: "Alert 4",
followusp: [
{
status: "new",
date: "now"
},
{
status: "canceled",
date: "now"
}
]
}
]

我想根据followups 数组中last 对象的状态对计数 进行分组。
所以对于给出的例子,结果应该是:

[
{
_id: "do_it",
count: 1
},
{
_id: "new",
count: 1
},
{
_id: "canceled",
count: 2
}
]

目前,我坚持使用以下解决方案(它不起作用):

query.push({ $group: { _id: "$followups.status", count: { $sum: 1 } } });
return dao.aggregate(query);

最佳答案

您可以使用 $let$arrayElemAt传递代表最后一个数组元素的 -1 来构建您的分组键:

db.collection.aggregate([
{
$group: {
_id: {
$let: {
vars: { last: { $arrayElemAt: [ "$followsup", -1 ] } },
in: "$$last.status"
}
},
count: { $sum: 1 }
}
}
])

Mongo Playground

关于javascript - Mongoose 按数组最后一个对象中的属性分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533736/

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