如何在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");

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

但这里的总体思路是使用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。