Java MongoDB聚合 - 多个字段的总和

时间:2017-09-11 17:10:32

标签: java mongodb aggregation-framework

我正在尝试使用Java执行mongodb聚合,无法弄清楚如何单独汇总2个字段。以下是我的文档结构:

"hello (world)".gsub!(/\([^)]+\)|\[[^\]]+\]/) do |bracketed|
  bracketed = "something different"
  "TEST!!!"
end

  # => "hello (TEST!!!)"

我试图总结使用:

{
    "_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()
);

当我运行此聚合时,缺陷的结果始终为NULL。

我希望结果为:

Aggregation pipeline = newAggregation(
        match(Criteria.where("time").gt(time)),
        group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"),
        project("total").and("defective").previousOperation()
);

以上是否可行,或者我应该执行2个单独的聚合?

1 个答案:

答案 0 :(得分:1)

您必须将累加器附加到组中。

这样的东西
Aggregation pipeline = newAggregation(
     match(Criteria.where("time").gt(time)),
     group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"),
     project("total","defective")
 );