【问题标题】:How to use "$match" and "$or" in mongo aggregation in java如何在java中的mongo聚合中使用“$match”和“$or”
【发布时间】:2017-05-22 12:41:09
【问题描述】:

我正在尝试使用聚合查询将匹配的文档加载到临时集合中。实际上,我可以将所有匹配的文档加载到 MongoDB 的临时集合中,但是我的 java 程序在 for 循环中抛出了 Null 指针异常。

我完全被困在这里了。我可以知道这种情况下出现空指针异常的原因吗?任何人都可以向我提出同样的建议......

 Document query = {"$or":[{"roll":1,"joiningDate":{"$gte":ISODate("2017-04-11T00:00:00Z")}},{"roll":2,"joiningDate":{"$gte": ISODate("2017-03-17T00:00:00Z")}}]};

            Document match = new Document("$match",new Document("$or",query));

            Document out =new Document("$out","TempCol");

            System.out.println("Before Aggregation");

            AggregateIterable<Document> resultAgg = collection.aggregate(Arrays.asList(match,out));

            System.out.println("After aggregation");

            for (Document doc : resultAgg){


                    System.out.println("The result of aggregation match:-");

            }

            System.out.println("Completed");

【问题讨论】:

    标签: java mongodb mongodb-query aggregation-framework


    【解决方案1】:

    我通常更喜欢将管道结构保持在一个变量中。

    但这里的总体思路是使用Document,你看到{}Arrays.asList,你看到[]

    List<Document> pipeline = Arrays.<Document>asList(
      new Document("$match",
        new Document("$or", Arrays.<Document>asList(
          new Document("roll", 1)
            .append("joiningDate", new Document(
              "$gte", new DateTime(2017,04,11,0,0,0, DateTimeZone.UTC).toDate()
            )),
          new Document("controlId", 2)
            .append("joiningDate", new Document(
              "$gte", new DateTime(2017,03,17,0,0,0, DateTimeZone.UTC).toDate()
            ))
        ))
      ),
      new Document("$out","TempCol")
    );
    
    AggregateIterable<Document> resultAgg = controlIssueCollection.aggregate(pipeline);
    

    还要确保在使用您最喜欢的构造方法(对我来说是org.joda.time.DateTime)构造Date 对象时,您使用的是UTC 时间,除非您真的有其他意思。如果您要与存储在 MongoDB 中的值进行比较,如 shell 中所示,那么您的意思是 UTC。

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2015-05-10
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      相关资源
      最近更新 更多