【发布时间】:2017-09-11 17:10:32
【问题描述】:
我正在尝试使用 Java 执行 mongodb 聚合,但无法弄清楚如何分别对 2 个字段求和。以下是我的文档结构:
{
"_id" : ObjectId("59b6b96423b65d0a04de128d"),
"itemCount": 25,
"defectiveItemCount": 5,
"time": ISODate("x")
},
{
"_id" : ObjectId("59b6b96423b65d0a04de128d"),
"itemCount": 20,
"defectiveItemCount": 7,
"time": ISODate("x")
}
我正在尝试使用:
Aggregation pipeline = newAggregation(
match(Criteria.where("time").gt(time)),
group().sum("itemCount").as("total"),
group().sum("defectiveItemCount").as("defective"),
project("total").and("defective").previousOperation()
);
我也试过了:
Aggregation pipeline = newAggregation(
match(Criteria.where("time").gt(time)),
group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"),
project("total").and("defective").previousOperation()
);
当我运行此聚合时,缺陷的结果始终为 NULL。
我想要的结果是:
{
"itemCount": 45,
"defectiveItemCount": 12
}
以上是否可行或者我应该执行 2 个单独的聚合?
【问题讨论】:
标签: java mongodb aggregation-framework