简体   繁体   中英

Compute a field in Mongo DB

Hey Guys here is a document in my collection. { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 }

There are close to 200 such documents. The Player_Rank field is a function of the total Weighted points, sorted in descending order. The player with the highest weighted points having rank 1 and so on. I have 2 use cases

  1. I need to display the rank to the user(player) when he logs into the webapp.
  2. I need to compute the fresh rank based on the match score every time a match takes place.

How do I compute this Rank field in Mongo DB. ? Can someone throw some light please.

Your question is not quite clear but i do have some suggestions for you.

For case 1:

it would be better if you assign some id with each player in order to get its other relevant details associated with him.

for now, let's assume that Player A has logged in with uid:123, you can use

var data  = db.player.find({}, {uid:123});
var rank = data.Player_Rank;

the rank of the player will be stored in rank variable which can be used anywhere in page.

For case 2:

After the input of points is inserted, sort the list with respect to points.

db.player.find().sort({Player_TotalWeightedPoints : -1})

now we have sorted the list, now we can assign player rank by using range from 1 to 200

db.players.aggregate([{
    $project: {
        "Player_Rank": { $range: [ 1, 200] }
    }
}])

this is the best which i can advice by looking at your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM