如何使用Java在MongoDB中使用AND和OR子句执行查询 [英] How to execute queries with both AND and OR clauses in MongoDB with Java
问题描述
我想在MongoDB 3.2中使用Java Driver 3.2执行查询,其中包含 $和
和 $或
同时使用条款。
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
应与 $或
连接,而在 criteria1
子句中<$ c应该应用$ c> $和。
Where the criteria1
and criteria2
should be connected with $or
while within criteria1
clause the $and
should be applied.
问题在于 MongoDB Java驱动程序
3.2有这样的方法,我得到无法解析方法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)
inMongoDB Java Driver
3.2?
- How can I compose a query such as
(A && B) || (X && Y)
inMongoDB Java Driver
3.2?
推荐答案
就我个人而言,我发现构造对象序列就像使用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)
)
);
基本上与以下内容相同:
Which is basically the same as:
{
"$or": [
{
"fetchStatus": {
"$gte": FetchStatus.PROCESS_NLP.getID(),
"$lte": fetchStatusParam
},
"episodeID": { "$in": episodeIDs }
},
{
"fetchStatus": PROCESSED_FETCH.getID(),
"isFullTextRet": false
}
]
}
此外,不需要显式 $ eq
运算符,因为equals实际上是值的默认含义无论如何,在查询属性中进行分配。
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屋!