如何使用 Java 在 MongoDB 中同时使用 AND 和 OR 子句执行查询? [英] How to execute queries with both AND and OR clauses in MongoDB with Java?
问题描述
我想使用 Java Driver 3.2 在 MongoDB 3.2 中执行查询,它同时包含 $and
和 $or
子句.
I want to execute query in MongoDB 3.2 with Java Driver 3.2, which contains both $and
and $or
clauses at the same time.
使用参考,我尝试了以下方法:
With the reference, I tried the following approach:
List<Document> criteria1 = new ArrayList<>();
List<Document> criteria2 = new ArrayList<>();
criteria1.add(new Document("fetchStatus", new Document("$gte", FetchStatus.PROCESSED_NLP.getID())));
criteria1.add(new Document("fetchStatus", new Document("$lte", fetchStatusParam)));
criteria1.add(new Document("episodeID", new Document("$in", episodeIDs)));
criteria2.add(new Document("fetchStatus", new Document("$eq", PROCESSED_FETCH.getID())));
criteria2.add(new Document("isFullTextRet", new Document("$eq", false)));
BasicDBList or = new BasicDBList();
or.add(criteria1);
or.add(criteria2);
DBObject query = new BasicDBObject("$or", or);
ArrayList<Document> results = dbC_Coll.find(query).into(new ArrayList<>());
criteria1
和 criteria2
应该与 $or
连接,而在 criteria1
子句中,$and
应该被应用.
Where the criteria1
and criteria2
should be connected with $or
while within criteria1
clause the $and
should be applied.
问题是在 MongoDB Java Driver 3.2 中没有这样的方法,我得到 Cannot resolve method find(com.mongodb.DBObject)
错误.
The problem is that in MongoDB Java Driver 3.2 there is such no method and I get the Cannot resolve method find(com.mongodb.DBObject)
error.
我的问题:
如何编写查询,例如 (A && B) ||(X && Y)
在 MongoDB Java Driver 3.2 中?
My question:
How can I compose a query such as (A && B) || (X && Y)
in MongoDB Java Driver 3.2?
推荐答案
就我个人而言,我发现像 U 一样使用 JSON 结构构建对象序列以增强可读性远没有那么令人困惑.但它仍然只是 Document()
无论你在哪里看到 {}
和 List
在你看到 []
的地方:>
Personally, I find it far less confusing to construct the object sequences just like U would with a JSON structure to enhance readability. But it's still just Document()
wherever you see {}
and List
wherever you see []
:
Document query = new Document(
"$or", Arrays.asList(
// First document in $or
new Document(
"fetchStatus",
new Document( "$gte", FetchStatus.PROCESSED_NLP.getID() )
.append("$lte", fetchStatusParam)
)
.append("episodeID", new Document( "$in", episodeIDs)),
// Second document in $or
new Document("fetchStatus", PROCESSED_FETCH.getID())
.append("isFullTextRet", false)
)
);
基本相同:
{
"$or": [
{
"fetchStatus": {
"$gte": FetchStatus.PROCESS_NLP.getID(),
"$lte": fetchStatusParam
},
"episodeID": { "$in": episodeIDs }
},
{
"fetchStatus": PROCESSED_FETCH.getID(),
"isFullTextRet": false
}
]
}
此外,也不需要显式"$eq
运算符,因为等于"实际上是查询属性中赋值的默认含义.
Also there is no need for "explicit" $eq
operators, since "equals" is actually the default meaning of a value assignment in a query property anyway.
这篇关于如何使用 Java 在 MongoDB 中同时使用 AND 和 OR 子句执行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!