mongoDB根据两个条件选择记录 [英] mongoDB selecting record based on two conditions
本文介绍了mongoDB根据两个条件选择记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库中的示例记录如下所示:
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
}
]
}
我正在尝试选择所有家庭作业分数> 90或考试分数
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);
这将取得所有分数> 90或<1的记录。但是没有涉及被检查分数应该是家庭作业分数或考试分数的条件。
我错过了一个将分数与类型联系起来的条件,然后检查它们的价值。
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.
谢谢,
John
Thanks, John
推荐答案
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))));
以这种方式使用。
这篇关于mongoDB根据两个条件选择记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文