根据排序顺序获取文档在集合中的位置 [英] Get document's placement in collection based on sort order
问题描述
我是MongoDB(+猫鼬)的新手.我收集了一些如下所示的高分文件:
I'm new to MongoDB (+Mongoose). I have a collection of highscores with documents that looks like this:
{id: 123, user: 'User14', score: 101}
{id: 231, user: 'User10', score: 400}
{id: 412, user: 'User90', score: 244}
{id: 111, user: 'User12', score: 310}
{id: 221, user: 'User88', score: 900}
{id: 521, user: 'User13', score: 103}
+ thousands more...
现在我正在获得前5名球员,如下所示:
now I'm getting the top 5 players like so:
highscores
.find()
.sort({'score': -1})
.limit(5)
.exec(function(err, users) { ...code... });
这很棒,但是我也想进行一个查询,例如"user12
在高分列表上有什么位置?"
which is great, but I would also like to make a query like "What placement does user12
have on the highscore list?"
以某种方式可以实现查询吗?
Is that possible to achieve with a query somehow?
推荐答案
可以使用 mapReduce ,但是它确实要求您在已排序字段上具有索引,因此,如果您尚未这样做,则首先:
It is possible to do this with mapReduce, but it does require that you have an index on the sorted field, so first, if you already have not done:
db.highscores.ensureIndex({ "score": -1 })
然后您可以执行以下操作:
Then you can do this:
db.highscores.mapReduce(
function() {
emit( null, this.user );
},
function(key,values) {
return values.indexOf("User12") + 1;
},
{
"sort": { "score": -1 },
"out": { "inline": 1 }
}
)
或者将其更改为您需要返回的信息,而不仅仅是排名"位置.但是,由于基本上是将所有内容放入一个已经按分数排序的大型数组中,所以对于任何合理大小的数据来说,它可能都不是最佳性能.
Or vary that to the information you need to return other than simply the "ranking" position. But since that is basically putting everything into a large array that has already been sorted by score then it probably will not be the best performance for any reasonable size of data.
一个更好的解决方案是维护一个单独的排名"集合,即使它没有进行任何减少,您也可以再次使用mapReduce进行定期更新:
A better solution would be to maintain a separate "rankings" collection, which you can again update periodically with mapReduce, even though it does not do any reducing:
db.highscores.mapReduce(
function() {
ranking++;
emit( ranking, this );
},
function() {},
{
"sort": { "score": -1 },
"scope": { "ranking": 0 },
"out": {
"replace": "rankings"
}
}
)
然后,您可以查询此集合以获取结果:
Then you can query this collection in order to get your results:
db.rankings.find({ "value.user": "User12 })
因此,该排名将在排名"集合的_id
字段中包含为已散发"的排名.
So that would contain the ranking as "emitted" in the _id
field of the "rankings" collection.
这篇关于根据排序顺序获取文档在集合中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!