Spring Data MongoDB使用reduce聚合报No property '$$value'异常如何解决
报错原因
- Spring Data MongoDB的聚合操作符API默认会对传入的字符串参数做实体类属性路径校验,你代码中使用的
$$value是$reduce操作的内置上下文变量,不属于业务实体类的字段,直接传入SetUnion.union()方法时,框架会尝试解析为实体类属性,找不到就抛出该异常。 - 你代码中
$reduce的初始值用了Collections.EMPTY_SET,和原生脚本的空数组类型不匹配,也可能引发额外的类型错误。
修复方案
你可以用Aggregation.literal()明确标记$$value为聚合字面量,跳过属性校验,同时修正初始值类型即可,修改后的代码如下:
ArrayOperators.Reduce reduce = ArrayOperators.Reduce.arrayOf("siteList") // 初始值和原生脚本保持一致,使用空数组 .withInitialValue(Collections.emptyList()) .reduce(SetOperators.SetUnion .arrayAsSet(StringOperators.valueOf("$$this.role").split(" ")) // 用literal标记$$value为内置变量,不做实体属性解析 .union(Aggregation.literal(ArrayOperators.Reduce.Variable.VALUE.getTarget())) ); ProjectionOperation projectionOperationOne = Aggregation.project() .andInclude("roleList") // 可自行补充需要保留的其他字段 .and(ConditionalOperators.ifNull(reduce).then(Collections.emptyList())).as("siteRoles"); ProjectionOperation projectionOperationTwo = Aggregation.project() // 可自行补充需要保留的其他字段 .and(SetOperators.SetDifference.arrayAsSet("roleList").differenceTo("siteRoles")).as("roleDiff"); Aggregation aggregation = Aggregation.newAggregation(projectionOperationOne, projectionOperationTwo); AggregationResults<SiteDiff> siteDiff = mongoTemplate.aggregate(aggregation, SampleCollection.class, SiteDiff.class);
如果使用的Spring Data MongoDB版本不支持上述写法,也可以直接通过构造Document的方式写聚合表达式,完全避开属性校验:
AggregationExpression reduceExpr = context -> new Document("$reduce", new Document("input", "$siteList") .append("initialValue", Collections.emptyList()) .append("in", new Document("$setUnion", Arrays.asList( "$$value", new Document("$split", Arrays.asList("$$this.role", " ")) ))) ); ProjectionOperation projectionOperationOne = Aggregation.project() .andInclude("roleList") .and(ConditionalOperators.ifNull(reduceExpr).then(Collections.emptyList())).as("siteRoles"); // 后续Stage和之前写法一致
你之前的业务逻辑没问题,只需要调整变量的识别规则就可以正常运行。
内容的提问来源于stack exchange,提问作者Mohammed Ashraf
相关产品推荐
相关产品推荐

