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

标签 javascript node.js mongodb mongoose

我有以下数据:

[
    {
        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/

相关文章:

node.js - Maven/Spring 与 Browserify : require is not defined

node.js - 在 angular2 quickstart 中安装 npm 的 Node 模块过多

mysql - MySQL 中 .query() 和 .execute() 的区别

javascript - 如何让 Bootstrap 模式对话框慢慢消失

javascript - Doppio:多线程如何工作?有什么限制吗?

sql - NoSQL 的用例

javascript - 如何使用 Nodejs 对远程 Mongodb 进行 CRUD 操作

mongodb - Go:创建 io.Writer 接口(interface)用于记录到 mongodb 数据库

javascript - 为什么在 reactjs 中需要 browser.min.js?

javascript - 从 Angular Directive(指令)调用 Controller 函数