【问题标题】:How to Query to achieve ranking documents with heighest points如何查询以实现得分最高的文档排名
【发布时间】:2021-01-02 21:53:30
【问题描述】:

在 MongoDB 中文档以这种格式保存。 我想以这样一种方式提取数据,即 userId 具有最高 Rank 的最大总点数。我是 MongoDB 的新手。请帮助我如何使用查询。

此数据保存在 MongoDB 中。

  [{
    _id:"33fa7277-d882-4add-9985-e92c3e48c15b",
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06141",
    points_total:280
},
{
    _id:"33fa7277-d882-4add-9985-e92c3e48c25b",
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06142",
    points_total:200
},
{
    _id:"33fa7277-d882-4add-9985-e92c3e48c35b",
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06141",
    points_total:20
},
{
    _id:"33fa7277-d882-4add-9985-e92c3e48c45b",
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06144",
    points_total:150
}]

我试过这个查询,但没有用。

db.users.aggregate([
    { "$sort": {"points_total" : -1}},
    { "$group": {
      "_id": "$user_id",
      "points_total":{"$sum": "$points_total"},
      "items": { "$push": "$$ROOT" }
    }},
    { "$unwind": { "path": "$items", "includeArrayIndex": "items.rank" } },
    { "$replaceRoot": { "newRoot": "$items" } },
    { "$sort": { "points_total" : -1} }
  ])

预期输出

[{
   
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06141",
    points_total:300,
    rank:1
},
{
  
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06142",
    points_total:200,
    rank:2
},
{
   
    user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06144",
    points_total:150,
    rank:3
}]

【问题讨论】:

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


    【解决方案1】:

    在申请$unwind之前,您还需要一个$group,以便将所有用户放在一个数组中:

    db.users.aggregate([
        {
            $group: {
                _id: "$user_id",
                points_total: { $sum: "$points_total" }
            }
        },
        {
            $sort: { points_total: -1 }
        },
        {
            $group: {
                _id: null,
                users: { $push: { user_id: "$_id", points_total: "$points_total" } }
            }
        },
        { "$unwind": { "path": "$users", "includeArrayIndex": "users.rank" } },
        {
            $replaceRoot: {
                newRoot: "$users"
            }
        },
        {
            $addFields: {
                rank:  { $add: [ "$rank", 1 ] }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

    • 谢谢,@mickl 我们可以选择从 1 而不是 0 开始排名。
    • @RahulSaini 你去吧:mongoplayground.net/p/ywUIVn_iCyk
    • 谢谢你拯救了我的一天。真的很感谢你的努力。谢谢。
    • 嗨@mickl 是否可以设置一个新的字段排名,然后将其当前数组索引增加1,而不是再次对所有内容进行分组?谢谢!
    • @LuisOrbaiceta 嘿,不确定您所说的“再次分组”是什么意思。第二个 $group 语句的原因是获取一个数组以便从 $unwind 中获取排名(文档需要是同一文档的一部分)。展开后不再分组,只有 1:1 的数据转换
    猜你喜欢
    • 2014-03-05
    • 2013-10-26
    • 2019-09-08
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多