node.js - $concatArrays 上的 MongoDB $sort

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我正在尝试将两个嵌套数组(使用 $concatArrays)连接到一个新字段中。我想通过两组对象中存在的属性对串联(Model.timeline)的输出进行排序。我似乎无法让它与 $unwind 一起工作。这是没有任何排序的查询:

Model.aggregate([
    {
        $match: {
            'id': id
        }
    },
    {
        $project: {
            id: 1,
            name: 1,
            flagged: 1,
            updatedAt: 1,
            lastEvent: {
                $arrayElemAt: ['$events', -1]
            },
            lastimage: {
                $arrayElemAt: ['$images', -1]
            },
            timeline: {
                $concatArrays: [
                    { $filter: {
                        input: '$events',
                        as: 'event',
                        cond: { $and: [
                            { $gte: ['$$event.timestamp', startAt] },
                            { $lte: ['$$event.timestamp', endAt] }
                        ]}
                    }},
                    { $filter: {
                        input: '$images',
                        as: 'image',
                        cond: { $and: [
                            { $gte: ['$$image.timestamp', startAt] },
                            { $lte: ['$$image.timestamp', endAt] }
                        ]}
                    }}
                ]
            }
        }
    }
]);

我是否遗漏了一些明显的东西?

最佳答案

在比赛和项目之后,您需要三个管道阶段。首先是$unwind,然后是$sort,最后是$group。使用 $first 运算符保留所有字段。

{
    $undwind : "$timeline",
},
{
    $sort : {"your.sortable.field" : 1}
},
{
    $group : {
        _id : "$_id",
        name : {$first : 1},
        flagged : {$first : 1},
        updatedAt : {$first : 1},
        lastEvent : {$first : 1},
        lastimage : {$first : 1},
        timeline : {$push : "$timeline"}
    }
}

请注意,即使您在比赛阶段后拥有多个文档,此功能也将起作用。所以基本上这将对每个文档中的数组元素进行排序。

关于node.js - $concatArrays 上的 MongoDB $sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875215/

相关文章:

node.js - 等效于 Node.JS 的 file_get_contents()

javascript - 如何发送数据正确的axios Error : Multipart: Boundary not found

mongodb索引嵌入字段(点表示法)

mongodb - 当集合之间存在关系时,mongodb 如何扩展?

javascript - 当该元素的值更改时,是否会自动重新执行从元素读取值的 Meteor Helper?

javascript - 我如何使用 Express/Mongoose 将模型引用到我的用户模型

node.js - 不将数据从服务方法传递到 mongoose get 路由以使用 Angular IO 查询数据

node.js - cassandra-driver (Node.js) 中同步查询执行的问题

javascript - Mongoose - 如何更新 MongoDB 数组中的所有对象?

node.js - 当还使用 GraphQL 时,Nodejs 和 Express 在 MERN 堆栈 Web 应用程序中的作用是什么?