Mongodb 根据mongo db中的点数查找用户排名

Mongodb 根据mongo db中的点数查找用户排名,mongodb,mongoose,aggregation-framework,ranking,Mongodb,Mongoose,Aggregation Framework,Ranking,我使用的是mongodb v4.2.1,具有以下模式 第一个集合:用户 { _id: mongoId, name: String, phone: {type: String, unique: true}, email: {type: String}, } 第二次收集:操作 { _id: mongoId, userId: String, // id from user collection actionType: Number, p

我使用的是mongodb v4.2.1,具有以下模式

第一个集合:用户

{
    _id: mongoId,
    name: String,
    phone: {type: String, unique: true},
    email: {type: String},
}
第二次收集:操作

{
    _id: mongoId,
    userId: String, // id from user collection
    actionType: Number,
    points: Number
}
action集合保留所有用户操作以及根据操作给出的一些点 **样本数据:**

[
  { _id: 5dd8c0bdf950e60c143136bd,
    userId: '5da6e2cc6b1d4b838ec36999',
    points: 5,
    __v: 0 },
  { _id: 5dd8c0ba96bd1543c65ad72c,
    userId: '5da6e2cc6b1d4b838ec36988',
    points: 5
    __v: 0 },
  { _id: 5dd8c0b86cb0a156cf5cb684,
    userId: '5da6e2cc6b1d4b838ec36999',
    points: 5}
]
我通过mongo aggregate找到了每个用户的总分,如下所示:

action.aggregate([
        { $match: {createdAt: { $gt: "2019-12-01"}} },
        { "$group": { _id: "$userId", points: { $sum: "$points" } } },
        { "$sort": { points: -1 } },
        { "$limit" : limit },
        // { "$lookup" :
        //   { from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }
        // }
    ]);
上面的查询为我提供了一系列顶级用户及其观点。我还根据用户在排序结果中的位置来获得排名靠前的用户

现在我想要的是根据userId获得特定用户的排名,我无法从排序数组中找到它,因为它可能有一百万用户

提前感谢。

您可以尝试:

  • 使用
    $group
    $limit
    后的结果放入数组中
  • 然后使用
    $unwind
    includearayindex
    选项获取索引
  • $match
    所需用户
  • 最后使用
    $project

  • 感谢您的努力,但像这样,我将获得特定用户的分数,我要寻找的是获得用户的排名,即用户在排序结果中的位置。
    const userId = '5da6e2cc6b1d4b838ec36988';
    
    action.aggregate([
            { $match: {createdAt: { $gt: "2019-12-01"}} },
            { "$group": { 
                _id: "$userId", 
                points: { $sum: "$points" },
              } 
            },
            { "$sort": { points: -1 } },
            { "$limit" : limit },
            // 1
            {
              "$group": { 
                _id: "",
                topusers: { $push: "$$ROOT" }
              }
            },
            // 2
            { "$unwind": { path: "$topusers", includeArrayIndex: "rank" } },
            // 3
            { "$match": { "topusers._id": userId } }
            // 4
            { "$project": {
                _id: "$topusers._id",
                points: "$topusers.points",
                rank: 1,
              } 
            }
    ]);