以下示例非常有效。
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>
您知道为什么它不起作用吗?
答案 0 :(得分:1)
项目和组操作都存在相同的问题。我将以porject操作为例。
您的方法projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
将返回ProjectOperation
。但是您没有将结果保存在变量中,因此聚合管道仅执行Aggregation.project("matches");
。
您可以尝试
ProjectionOperation projectionOperation = Aggregation.project("matches");
for(String typeOfShots : typesOfShots) {
projectionOperation = projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
}