【问题标题】:How to use MongoDB Aggegation GroupOperation Method in JAVA如何在 JAVA 中使用 MongoDB 聚合 GroupOperation 方法
【发布时间】:2021-10-21 05:23:29
【问题描述】:

我有一个查询并使用基于条件的计数,而在 java 中我使用的是聚合 GroupOperation 对象。那么如何用JAVA写这个语句呢? 示例查询:

{
    $group: {
      _id: {
        "categoryCode": "$categoryCode",
        "categoryName": "$categoryName"
      },
      "cat_count": {
        $sum: {
          $cond: [{ $eq: ["$cat_type", "A"] }, 1, 0]
        }
      }
    }
  }

【问题讨论】:

    标签: java spring spring-boot spring-data-mongodb


    【解决方案1】:

    您可以使用 org.springframework.data.mongodb.core.aggregation 包中的聚合类来编写此查询。

    ConditionalOperators.Cond cond = ConditionalOperators.Cond.when(ComparisonOperators.Eq.valueOf("$cat_type").equalToValue("A"))
                .then(1)
                .otherwise(0);
    GroupOperation groupOperation = Aggregation.group("categoryCode", "categoryName").sum(cond).as("cat_count");
    

    现在使用这个 groupOperation 和 mongotemplate 来执行查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      相关资源
      最近更新 更多