mongoDB selecting record based on two conditions

霸气de小男生 提交于 2019-12-22 01:37:54

问题


A sample record in my database looks like :

{
    "_id" : 2,
    "name" : "Corliss Zuk",
    "scores" : [
            {
                    "type" : "exam",
                    "score" : 87.53859552156015
            },
            {
                    "type" : "quiz",
                    "score" : 24.49132971110967
            },
            {
                    "type" : "homework",
                    "score" : 99.24881912510654
            }
    ]

}

I am trying to select all records that have homework scores > 90 or exam scores < 50. My OR condition is like this:

 DBObject clause1 = new BasicDBObject("scores.type", "homework").append("scores.score", new BasicDBObject("$gt", 90)); 
    DBObject clause2 = new BasicDBObject("scores.type", "exam").append("scores.score", new BasicDBObject("$lt", 50));    
    BasicDBList or = new BasicDBList();
    or.add(clause1);
    or.add(clause2);
    DBObject query = new BasicDBObject("$or", or);

This is picking up all records where the score is > 90 or < 50 but not relating the condition that the score being examined should be either a homework score or an exam score. I am missing a condition that will relate the scores to the type and then examine their value.

Any help would be much appreciated.

Thanks, John


回答1:


DBObject clause1 = new BasicDBObject("scores", new BasicDBObject("$elemMatch", new BasicDBObject("type", "homework").append("score", new BasicDBObject("$gt", 90))));
DBObject clause2 = new BasicDBObject("scores", new BasicDBObject("$elemMatch", new BasicDBObject("type", "exam").append("score", new BasicDBObject("$lt", 50))));

Use it this way.




回答2:


You're currently effectively doing this :

find({
   $or:[
      {
         'scores.type':"exam",
         'scores.score':{
            $lt:50
         }
      },
      {
         'scores.type':"homework",
         'scores.score':{
            $gt:90
         }
      }
   ]
})

This is basically asking MongoDB to return any document where ANY element has a type "exam" and ANY element has a score higher than 50.0 but not necessarily the same element.

You can use the $elemMatch operator to test multiple criteria against the same element. As such the Java equivalent of this will do the trick :

find({
   $or:[
      {
         scores:{
            $elemMatch:{
               type:"exam",
               score:{
                  $lt:50
               }
            }
         }
      },
      {
         scores:{
            $elemMatch:{
               type:"homework",
               score:{
                  $gt:90
               }
            }
         }
      }
   ]
})

Hope that helps.



来源:https://stackoverflow.com/questions/16806348/mongodb-selecting-record-based-on-two-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!