stef
stef

Reputation: 1528

How can i get the position of a record in a mongo query / collection?

Say, for example, I have a leaderboard in MongoDB. The following query would get a segment of the leaderboard:

db.leaderboard.find().sort({ score: -1 }).limit(30)

What if i had a leaderboard entry, with an _id of, say, a:

db.leaderboard.find({ _id: 'a' })

How would i go about finding the position of that record on the leaderboard?

Upvotes: 3

Views: 2871

Answers (1)

Christian P
Christian P

Reputation: 12240

It's easy. First, find the score for the target record:

db.leaderboard.find({ _id: 'a' }, {score : 1, _id : 0});

Then count all the documents that have score greater than the target score:

db.leaderboard.find({ score : { $gt : 100 /* targetScore */ } }).count();  

Your position will be +1 of the count. One caveat: if there are multiple documents with the same score as the target score your position will probably be "wrong".

An example: when you sort your documents by using sort and you have 3 documents. Let's say the they are in 7,8 and 9 "position". Your document with _id : 'a' can be on any of these "positions".

Upvotes: 6

Related Questions