mongodb - How can i get the position of a record in a mongo query / collection? -
say, example, have leaderboard in mongodb. following query segment of leaderboard:
db.leaderboard.find().sort({ score: -1 }).limit(30)
what if had leaderboard entry, _id
of, say, a
:
db.leaderboard.find({ _id: 'a' })
how go finding position of record on leaderboard?
it's easy. first, find score target record:
db.leaderboard.find({ _id: 'a' }, {score : 1, _id : 0});
then count documents have score greater target score:
db.leaderboard.find({ score : { $gt : 100 /* targetscore */ } }).count();
your position +1 of count. 1 caveat: if there multiple documents same score target score position "wrong".
an example: when sort documents using sort , have 3 documents. let's in 7,8 , 9 "position". document _id : 'a'
can on of these "positions".
Comments
Post a Comment