如何使用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驱动程序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)
在MongoDB Java驱动程序3.2中?
My question:
How can I compose a query such as (A && B) || (X && Y)
in MongoDB Java Driver 3.2?
推荐答案
就个人而言,我发现构造对象序列的混乱要少得多,就像U用JSON结构来增强可读性一样.但是无论您在何处看到 {}
,还是在任何地方,只要看到 []
, List
仍然是 Document()
:>
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屋!