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

Mik*_* B. 4 java mongodb mongodb-query mongo-java-driver

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

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

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<>());
Run Code Online (Sandbox Code Playgroud)

criteria1andcriteria2应该与$orwhile 内的criteria1子句连接时,$and应该应用。

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

我的问题:
如何(A && B) || (X && Y)在 MongoDB Java Driver 3.2 中编写查询?

Nei*_*unn 5

就我个人而言,我发现像 U 一样使用 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)
    )
);
Run Code Online (Sandbox Code Playgroud)

这与以下内容基本相同:

   {
       "$or": [
           {
               "fetchStatus": { 
                   "$gte": FetchStatus.PROCESS_NLP.getID(),
                   "$lte": fetchStatusParam
               },
               "episodeID": { "$in": episodeIDs }
           },
           {
               "fetchStatus": PROCESSED_FETCH.getID(),
               "isFullTextRet": false
           }
       ]
   }
Run Code Online (Sandbox Code Playgroud)

也不需要“显式”$eq运算符,因为“等于”实际上是查询属性中值分配的默认含义。