我有以下数据:
[
{
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 }
}
}
])
关于javascript - Mongoose 按数组最后一个对象中的属性分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533736/