简体   繁体   English

Mongo DB中的嵌套查询

[英]Nested Query in Mongo DB

Here's my schema: 这是我的架构:

var playerScheme = new Schema({
    _id:String,
    score:Number
    }

Im trying to get the rank of each player by counting the number of users with more points than the user in question, say user X. I get passed the user id of x in the res parameter. 我试图通过计算比问题用户(例如用户X)得分更高的用户数来获得每个玩家的排名。我在res参数中传递了x的用户ID。 I use the following query but cant figure out how to nest another find query after $gt to get the score for player x. 我使用以下查询,但无法弄清楚如何在$ gt之后嵌套另一个查找查询,以获取玩家x的得分。

This is my code in node using Mongoose: 这是我在使用Mongoose的节点中的代码:

exports.getRankForUser = function(req,res) {

  var userId = ObjectId(req.body.userId); 
  var rank;

  playerModel.player.count({"score" :{$gt: GET SCORE FOR USERID QUERY}})
    .exec(function(err,result)
    {
      if(err) {
        res.send(err ,500);
      } else {
        res.send(result,200);
      }
    }
);

}

First, you must get the user X information. 首先,您必须获取用户X信息。 Once you have that information, you can perform a nested count query inside the first callback, using the obtained user X info as follows: 获得这些信息后,可以使用获得的用户X信息,在第一个回调内执行嵌套计数查询,如下所示:

exports.getRankForUser = function(req,res) {

  var userId = ObjectId(req.body.userId); 
  var rank;

  playerModel.player.findById(userId, function(err, user){
      if(err){
          res.send(err ,500);
      }else if (!user){
          res.send('The requested user does not exist' ,404);
      }else{
          //At this point, you have the user X info in the var "user". 
          //Just query the count with a nested query
          playerModel.player.count({score: {$gt: user.score}})
          .exec(function(err, result){
              if(err) {
                  res.send(err ,500);
              } else {
                  //Here you are returning the number of users that 
                  //has a score value higher than the user X score.
                  res.send(result,200);
              }
          });
      }
  });

}

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

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