如何在Mongoose中按多个字段排序的列表中的项目排名

kon*_*hou 7 ranking mongoose mongodb

我在MongoDB集合中有许多用户记录(> 10000),可以按分数desc + time asc + bonus desc进行排序.如何使用Mongoose根据此排序获取列表中一个用户的排名?假设索引已正确构建.

wdb*_*ley 14

计算排序顺序中此用户之前的用户数.我将从简单(非复合排序)的情况开始,因为复合情况下的查询更复杂,即使这个想法完全相同.

> db.test.drop()
> for (var i = 0; i < 10; i++) db.test.insert({ "x" : i })
> db.test.find({ }, { "_id" : 0 }).sort({ "x" : -1 }).limit(5)
{ "x" : 9 }
{ "x" : 8 }
{ "x" : 7 }
{ "x" : 6 }
{ "x" : 5 }
Run Code Online (Sandbox Code Playgroud)

对于这个命令,文档的排名{ "x" : i }是文件的数量{ "x" : j }i < j

> var rank = function(id) {
    var i = db.test.findOne({ "_id" : id }).x
    return db.test.count({ "x" : { "$gt" : i } })
}
> var id = db.test.findOne({ "x" : 5 }).id
> rank(id)
4
Run Code Online (Sandbox Code Playgroud)

该排名将在0基于同样,如果您要计算文档等级{ "x" : i }的排序{ "x" : 1 },你会算文档的数量{ "x" : j }i > j.

对于复合排序,相同的程序工作,但它是棘手的实现,因为在一个复合索引的顺序是字典,即用于排序{ "a" : 1, "b" : 1},(a, b) < (c, d)如果a < c还是a = cb < d,所以我们需要一个更复杂的查询,以表达这一条件.以下是复合索引的示例:

> db.test.drop()
> for (var i = 0; i < 3; i++) {
    for (var j = 0; j < 3; j++) {
        db.test.insert({ "x" : i, "y" : j })
    }
}
> db.test.find({}, { "_id" : 0 }).sort({ "x" : 1, "y" : -1 })
{ "x" : 0, "y" : 2 }
{ "x" : 0, "y" : 1 }
{ "x" : 0, "y" : 0 }
{ "x" : 1, "y" : 2 }
{ "x" : 1, "y" : 1 }
{ "x" : 1, "y" : 0 }
{ "x" : 2, "y" : 2 }
{ "x" : 2, "y" : 1 }
{ "x" : 2, "y" : 0 }
Run Code Online (Sandbox Code Playgroud)

要查找文档的排名{ "x" : i, "y" : j },你需要找到的文档数{ "x" : a, "y" : b }的顺序{ "x" : 1, "y" : -1 }这样(i, j) < (a, b).鉴于排序规范,这相当于条件i < ai = aj > b:

> var rank = function(id) {
    var doc = db.test.findOne(id)
    var i = doc.x
    var j = doc.y
    return db.test.count({
        "$or" : [
            { "x" : { "$lt" : i } },
            { "x" : i, "y" : { "$gt" : j } }
        ]
    })
}
> id = db.test.findOne({ "x" : 1, "y" : 1 })._id
> rank(id)
4
Run Code Online (Sandbox Code Playgroud)

最后,在你的三部分复合指数的情况下

{ "score" : -1, "time" : 1, "bonus" : -1 }
Run Code Online (Sandbox Code Playgroud)

rank功能将是

> var rank = function(id) {
    var doc = db.test.findOne(id)
    var score = doc.score
    var time = doc.time
    var bonus = doc.bonus
    return db.test.count({
        "$or" : [
            { "score" : { "$gt" : score } },
            { "score" : score, "time" : { "$lt" : time } },
            { "score" : score, "time" : time, "bonus" : { "$gt" : bonus } }
        ]
    })
}
Run Code Online (Sandbox Code Playgroud)