Javascript Mongoose数组最后一个对象中的group by属性
我有以下数据:Javascript Mongoose数组最后一个对象中的group by属性,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有以下数据: [ { name: "Alert 1", followusp: [ { status: "new", date: "now" }, { status: "do_it", date: "now" } ]
[
{
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数组中最后一个对象的状态分组并获取计数。因此,对于给定的示例,结果应为:
[
{
_id: "do_it",
count: 1
},
{
_id: "new",
count: 1
},
{
_id: "canceled",
count: 2
}
]
目前,我坚持使用以下解决方案(它不起作用):
您可以使用并传递表示生成分组键的最后一个数组元素的-1
:
db.collection.aggregate([
{
$group: {
_id: {
$let: {
vars: { last: { $arrayElemAt: [ "$followsup", -1 ] } },
in: "$$last.status"
}
},
count: { $sum: 1 }
}
}
])
db.collection.aggregate([
{
$group: {
_id: {
$let: {
vars: { last: { $arrayElemAt: [ "$followsup", -1 ] } },
in: "$$last.status"
}
},
count: { $sum: 1 }
}
}
])