如何使用Java在MongoDB中使用AND和OR子句执行查询

我想在MongoDB 3.2中使用Java Driver 3.2执行查询,它同时包含$and$or子句。

通过参考 ,我尝试了以下方法:

 List criteria1 = new ArrayList(); List 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 results = dbC_Coll.find(query).into(new ArrayList()); 

如果criteria1criteria2应与$or criteria1条款相关联$and则应使用$and

问题是在MongoDB Java Driver 3.2中有没有这样的方法,我得到了Cannot resolve method find(com.mongodb.DBObject)错误。

我的问题:

  • 如何撰写查询,例如(A && B) || (X && Y) MongoDB Java Driver 3.2中的(A && B) || (X && Y)

就个人而言,我发现构建对象序列就像使用JSON结构来增强可读性一样容易混淆。 但它仍然只是Document()只要你看到{}List无论你在哪里看到[]

 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运算符,因为“equals”实际上是查询属性中值赋值的默认含义。