如何使用Java驱动程序为MongoDB构建$或查询? [英] How can I build an $or query for MongoDB using the Java driver?
问题描述
我正在尝试使用MongoDB中的某些条件(使用Java驱动程序)。这就是我正在做的事情:
Pattern regex = Pattern.compile(title);
DBCollection coll = MongoDBUtil.getDB()。getCollection(post_details);
BasicDBObject query = new BasicDBObject();
query.put(category_title,myCategory);
query.append(post_title,regex);
query.append(post_description,regex);
DBCursor cur = coll.find(query);
while(cur.hasNext()){
System.out.println(cur.next()。get(post_id));
}
我想使用 $或
这些条件下的操作数,但我猜默认是和,我不知道如何更改它。在上面的代码中,如果其中一个条件返回 null
,结果也将是 null
。
你是正确的,在查询中指定多个字段的默认是每个字段用作条件过滤器,因此是一个AND使用具有以下语法的$或操作数,可以使用OR子句执行MongoDB查询:
db.col.find({$ or:[clause1,clause2]})
其中每个子句都可以是查询。 $或者不必是顶级操作数,但如果是MongoDB,则可以为每个单独的子句使用索引。
在您的示例中,您希望以此结束查询:
db.col.find({$ or:[{post_title,regex},{post_description,正则表达式}]});
可以用Java构建:
DBObject clause1 = new BasicDBObject(post_title,regex);
DBObject clause2 = new BasicDBObject(post_description,regex);
BasicDBList或= new BasicDBList();
or.add(clause1);
or.add(第2条);
DBObject query = new BasicDBObject($ or,or);
I'm trying to Or some conditions in MongoDB (using the Java driver). This is what I'm doing :
Pattern regex = Pattern.compile("title");
DBCollection coll = MongoDBUtil.getDB().getCollection("post_details");
BasicDBObject query = new BasicDBObject();
query.put("category_title", "myCategory");
query.append("post_title", regex);
query.append("post_description", regex);
DBCursor cur = coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next().get("post_id"));
}
I'd like to use the $or
operand on these conditions, but I guess the default is "and" and I don't know how to change it. In the above code if one of the conditions returns null
, the result will be null
too.
You are correct that the "default" for specifying multiple field in a query is that each field serves as a conditional filter, and thus is an AND operation.
You can perform MongoDB queries with an OR clause by using the $or operand which has the following syntax :
db.col.find({$or:[clause1, clause2]})
Where each clause can be a query. $or does not have to be a top level operand but if it is MongoDB can use an index for each seperate clause.
In your example you want to end up with this query :
db.col.find({$or:[{"post_title", regex}, {"post_description", regex}]});
Which can be constructed in Java through :
DBObject clause1 = new BasicDBObject("post_title", regex);
DBObject clause2 = new BasicDBObject("post_description", regex);
BasicDBList or = new BasicDBList();
or.add(clause1);
or.add(clause2);
DBObject query = new BasicDBObject("$or", or);
这篇关于如何使用Java驱动程序为MongoDB构建$或查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!