首页 > 解决方案 > 总结所有文档的字段值

问题描述

我想在 mongoDB 中的所有文档中总结一个字段值,所以尝试了带有 null 字段的 $group 然后$sum. 它给出了预期的结果,但是当我同样尝试使用 mongoOperation 在 Java 中进行转换时,会出现错误,因为组值不能为空或为空。

以下是我收藏中的数据:

{ "_id" : ObjectId("5c583ee7c1299106eaeec6bf"), "_class" : "com.health", "startTime" : ISODate("2019-02-04T13:02:00Z"), "endTime" : ISODate("2019-02-04T13:32:23.958Z"), "agentStatsList" : [ { "Name" : "ABC", "totalRefresh" : 103, "success" : 87, "failure" : 16 }, { "Name" : "PQR", "totalRefresh" : 19, "success" : 10, "failure" : 9 }, { "Name" : "XYZ", "totalRefresh" : 14, "success" : 13, "failure" : 1 }]}

UnwindOperation unwind=Aggregation.unwind("agentStatsList");
MatchOperation match=Aggregation.match(Criteria.where("agentStatsList.agentName").in(listOfAgents).
            and("startTime").lte(new Date(System.currentTimeMillis() - 3600 * 1000)));      
GroupOperation group=Aggregation.group("").sum("agentStatsList.success").as("success").sum("agentStatsList.failure").as("failure").
sum("agentStatsList.totalRefresh").as("totalRefresh");
Aggregation aggregation=Aggregation.newAggregation(unwind,match,group);

Shell Query 工作正常,但在 java 中它不工作。

标签: javamongodb

解决方案


推荐阅读