有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mongodb如何在java中的mongo聚合中使用“$match”和“$or”

我正在尝试使用聚合查询将匹配的文档加载到临时集合中。实际上,我能够将所有匹配的文档加载到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");

共 (1) 个答案

  1. # 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);
    

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