如何使用 for 循环构建 Spring 数据 Mongo 聚合操作

How build Spring Data Mongo Aggregation Operations using for-loop

以下示例完美运行。

    MatchOperation matchStage = mongodbConstructorQueryUtils.makeMatchStage(topCriteria);

        GroupOperation groupStage = Aggregation.group("teamId", "teamName")
            .sum("shotsOfOneAttempted").as("sumShotsOfOneAttempted")
            .sum("shotsOfTwoAttempted").as("sumShotsOfTwoAttempted")
            .sum("shotsOfThreeAttempted").as("sumShotsOfThreeAttempted")
            .addToSet("idMatchCallExt").as("matches");

        ProjectionOperation projectionOperation = Aggregation.project("matches")
            .and("sumShotsOfOneAttempted").as("sumShotsOfOneAttempted")
            .and("sumShotsOfTwoAttempted").as("sumShotsOfTwoAttempted")
            .and("sumShotsOfThreeAttempted").as("sumShotsOfThreeAttempted")
            .and("matches").size().as("sumMatches");

        Aggregation agg = Aggregation.newAggregation(
                matchStage,
                groupStage,
                projectionOperation
        );

for 循环示例:

    MatchOperation matchStage = mongodbConstructorQueryUtils.makeMatchStage(topCriteria);

    GroupOperation groupStage = Aggregation.group("teamId", "teamName");
    for(String typeOfShots : typesOfShots) {
        groupStage.sum(typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
    }
    groupStage.addToSet("idMatchCallExt").as("matches");

    ProjectionOperation projectionOperation = Aggregation.project("matches");

    for(String typeOfShots : typesOfShots) {
        projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
    }

    Aggregation agg = Aggregation.newAggregation(
            matchStage,
            groupStage,
            projectionOperation
    );

没用。它只是用 teamId 和 teamName 构建 groupStage,并且 projectionOperation 找不到匹配项等等...

我对 spring.mongodb 的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

你知道为什么它不起作用吗?

你的项目和组操作都是一样的问题。我将以项目操作为例。

您的方法 projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted"); 将 return 变成 ProjectOperation。但是您没有将结果保存在变量中,因此聚合管道仅执行 Aggregation.project("matches");

相反,您可以尝试

ProjectionOperation projectionOperation = Aggregation.project("matches");

for(String typeOfShots : typesOfShots) {
    projectionOperation = projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
}