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?