简体   繁体   English

在 Mongo DB 中计算一个字段

[英]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 } { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 }

There are close to 200 such documents.此类文件有近 200 份。 The Player_Rank field is a function of the total Weighted points, sorted in descending order. Player_Rank 字段是总加权点数的 function,按降序排列。 The player with the highest weighted points having rank 1 and so on.权重最高的玩家排名第一,依此类推。 I have 2 use cases我有 2 个用例

  1. I need to display the rank to the user(player) when he logs into the webapp.当他登录到 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.如何在 Mongo DB 中计算此 Rank 字段。 ? ? Can someone throw some light please.有人可以请放一些光。

Your question is not quite clear but i do have some suggestions for you.你的问题不是很清楚,但我确实有一些建议给你。

For case 1:对于案例 1:

it would be better if you assign some id with each player in order to get its other relevant details associated with him.如果您为每个玩家分配一些 id 以获得与他相关的其他相关详细信息,那会更好。

for now, let's assume that Player A has logged in with uid:123, you can use现在,假设玩家 A 使用 uid:123 登录,您可以使用

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:对于案例 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现在我们已经对列表进行了排序,现在我们可以使用从 1 到 200 的范围来分配玩家排名

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

this is the best which i can advice by looking at your question.这是最好的,我可以通过查看您的问题来提供建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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