mongoDB selecting record based on two conditions

℡╲_俬逩灬. 提交于 2019-12-04 19:45:37
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.

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.

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