javascript - Get document's placement in collection based on sort order -


i'm new mongodb (+mongoose). have collection of highscores documents looks 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... 

now i'm getting top 5 players so:

highscores     .find()     .sort({'score': -1})     .limit(5)     .exec(function(err, users) { ...code... }); 

which great, make query "what placement user12 have on highscore list?"

is possible achieve query somehow?

it possible mapreduce, require have index on sorted field, first, if have not done:

db.highscores.ensureindex({ "score": -1 }) 

then can 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 information need return other "ranking" position. since putting large array has been sorted score not best performance reasonable size of data.

a better solution maintain separate "rankings" collection, can again update periodically mapreduce, though not reducing:

db.highscores.mapreduce(     function() {         ranking++;         emit( ranking, );     },     function() {},     {         "sort": { "score": -1 },         "scope": { "ranking": 0 },         "out": {             "replace": "rankings"         }     } ) 

then can query collection in order results:

db.rankings.find({ "value.user": "user12 }) 

so contain ranking "emitted" in _id field of "rankings" collection.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -