【问题标题】:Java MongoDB aggregation - sum of multiple fieldsJava MongoDB聚合 - 多个字段的总和
【发布时间】: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


    【解决方案1】:

    您必须在组中附加累加器。

    类似

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2013-07-23
      相关资源
      最近更新 更多