MongoDB按自定义字段排序集合

时间:2017-08-17 08:24:21

标签: mongodb mongoose aggregation-framework database

我有聚合查询,如下所示:

aggregate.append([
            {$sort: paginateOptions.sort},
            {$match: paginateOptions.match},
            {$skip: (paginateOptions.page - 1) * paginateOptions.limit},
            {$limit: paginateOptions.limit},
            {
                $lookup: {
                    from: 'users',
                    localField: 'owner',
                    foreignField: '_id',
                    as: 'owner'
                }
            },
            {
                $unwind: {
                    path: '$owner',
                    preserveNullAndEmptyArrays: true
                }
            },
            {
                $project: {
                    name: {
                        $concat: ["$firstname", " ", "$lastname"]
                    },
                    email: 1,
                    owner: {
                        _id: 1,
                        username: 1
                    },
                    last_note: {
                        $arrayElemAt: ["$notes", -1]
                    }
                }
            }
        ])

我想按最后一个音符时间字段(last_note.time)排序。 问题是,这个字段是在项目过程中创建的,如果我要在项目之后添加一个排序,我将只对限制文档进行排序,而不是整个集合(因为它将在限制之后)跳过..)

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您应该在跳过和限制之前排序:

 `[
{$match: paginateOptions.match},
{$lookup: {
                from: 'users',
                localField: 'owner',
                foreignField: '_id',
                as: 'owner'
            }
        },
{$unwind: {
                path: '$owner',
                preserveNullAndEmptyArrays: true
            }
        },
{$project: {
                name: {
                    $concat: ["$firstname", " ", "$lastname"]
                },
                email: 1,
                owner: {
                    _id: 1,
                    username: 1
                },
                last_note: {
                    $arrayElemAt: ["$notes", -1]
                }
            }
 },
 {$sort: paginateOptions.sort},
 {$skip: (paginateOptions.page - 1) * paginateOptions.limit},
 {$limit: paginateOptions.limit},
    ]`