[英]Java MongoDB aggregation - sum of multiple fields
I am trying to perform a mongodb aggregation using Java and unable to figure out how to sum 2 fields individually. 我正在尝试使用Java执行mongodb聚合,并且无法弄清楚如何分别汇总2个字段。 Below is my document structure:
下面是我的文档结构:
{
"_id" : ObjectId("59b6b96423b65d0a04de128d"),
"itemCount": 25,
"defectiveItemCount": 5,
"time": ISODate("x")
},
{
"_id" : ObjectId("59b6b96423b65d0a04de128d"),
"itemCount": 20,
"defectiveItemCount": 7,
"time": ISODate("x")
}
I am trying to sum using: 我试图总结使用:
Aggregation pipeline = newAggregation(
match(Criteria.where("time").gt(time)),
group().sum("itemCount").as("total"),
group().sum("defectiveItemCount").as("defective"),
project("total").and("defective").previousOperation()
);
I also tried: 我也尝试过:
Aggregation pipeline = newAggregation(
match(Criteria.where("time").gt(time)),
group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"),
project("total").and("defective").previousOperation()
);
When I run this aggregation, the result of defective is always NULL. 当我运行此聚合时,有缺陷的结果始终为NULL。
I want the result as: 我想要的结果是:
{
"itemCount": 45,
"defectiveItemCount": 12
}
Is the above possible or should I perform 2 separate aggregations? 以上是否可行,还是应该执行2个单独的汇总?
You have to append the accumulators in group. 您必须将累加器添加到组中。
Something like 就像是
Aggregation pipeline = newAggregation(
match(Criteria.where("time").gt(time)),
group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"),
project("total","defective")
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.