Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose数组最后一个对象中的group by属性_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

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 }
        }
    }
])