Mongodb 如何使用for循环构建Spring数据Mongo聚合操作
下面的示例非常有效Mongodb 如何使用for循环构建Spring数据Mongo聚合操作,mongodb,spring-data-mongodb,spring-mongodb,Mongodb,Spring Data Mongodb,Spring Mongodb,下面的示例非常有效 MatchOperation matchStage = mongodbConstructorQueryUtils.makeMatchStage(topCriteria); GroupOperation groupStage = Aggregation.group("teamId", "teamName") .sum("shotsOfOneAttempted").as("sumShotsOfOneAttempted")
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>
你知道为什么它不起作用吗?你在项目和团队运作方面都有同样的问题。我将以porject操作为例 您的方法ProjectOnOperation.andsum+typeOfShots+Attempted.assum+typeOfShots+Attempted;将返回一个项目操作。但是您没有将结果保存在变量中,因此只有Aggregation.projectmatches;由聚合管道执行 相反,你可以试试
ProjectionOperation projectionOperation = Aggregation.project("matches");
for(String typeOfShots : typesOfShots) {
projectionOperation = projectionOperation.and("sum"+typeOfShots+"Attempted").as("sum"+typeOfShots+"Attempted");
}
尝试应该尝试,我错了吗?是的,我要编辑这个问题。谢谢。