0

The following example works perfectly.

    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
        );

Example with for-loops:

    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
    );

It doesn't work. It just build groupStage with teamId and teamName, and projectionOperation failds to found matches and so on...

My depndendencies of spring.mongodb:

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

Do you know why it doesn't work?

charlycou
  • 1,778
  • 13
  • 37
vlarios
  • 31
  • 8

1 Answers1

1

You have the same problem for both project and group operation. I'll take the porject operation as an example.

Your method projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted"); will return a ProjectOperation. But your not saving your result in your variable so only Aggregation.project("matches"); is executed by the aggregation pipeline.

Instead you could try

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

for(String typeOfShots : typesOfShots) {
    projectionOperation = projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
}
charlycou
  • 1,778
  • 13
  • 37