【问题标题】:How to execute queries with both AND and OR clauses in MongoDB with Java?如何使用 Java 在 MongoDB 中使用 AND 和 OR 子句执行查询?
【发布时间】:2016-08-13 16:33:23
【问题描述】:

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

使用reference,我尝试了以下方法:

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<>());

criteria1criteria2 应与 $or 连接,而在 criteria1 子句中应应用 $and

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

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

【问题讨论】:

    标签: java mongodb mongodb-query mongo-java-driver


    【解决方案1】:

    就我个人而言,我发现像 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)
        )
    );
    

    基本相同:

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2019-10-03
      • 2018-12-08
      相关资源
      最近更新 更多