首页 > 解决方案 > 聚合排序后如何找出项目的索引?

问题描述

我希望能够在其输出中显示项目的索引。

这是我现在的代码:

Picks.aggregate([
    { 
        "$group": { 
            _id: "$user.uid", 
            name: { 
                $first: "$user.name" 
            }, 
            total: { 
               $sum: "$total" 
            },
        } 
    }, 
    { 
        "$sort": { 
            "total": -1 
        } 
    }, 
    { 
        "$limit": 10 
    }
])

我对使用聚合没有任何问题,我可以对需要的字段进行分组。这是一个示例输出,我已经注释掉了我正在寻找的内容。

[
    {
        _id: "1a2b3c4d5e6f7g8h9i",
        name: "Jane Doe",
        total: 7384,
        // next line is what I'm looking for
        // rank: 0 <-- it's the first item in an array after $sort
    },
    {
        _id: "a1b2c3d4e5f6g7h8i9",
        name: "John Doe",
        total: 7370,
        // next line is what I'm looking for
        // rank: 1 <-- it's the second item in an array after $sort
    },
    ...
]

标签: javascriptnode.jsmongodbmongooseaggregation-framework

解决方案


推荐阅读