Spring Data聚合投影中查询数组元素存在性的问题
解决MongoDB聚合计算字段判断数组包含元素的问题
你的代码里计算字段"like"始终返回false,核心问题是数组匹配条件用错了:你用Criteria.where("lstLikeUserid").is(userId)来判断用户ID是否在数组中,但is()是用来匹配整个字段完全等于给定值的——对于数组类型的字段,它会检查整个数组是否和你传入的单个字符串完全相等(这显然不成立),所以不管数组里有没有目标ID,条件都会判定为false。
修正后的代码实现
我们需要用MongoDB的$in操作符来判断值是否存在于数组中,在Spring Data MongoDB里可以通过AggregationExpressions.in()来构建这个条件,代码如下:
String userId = "5992dc5725ac203acfa101e6"; // 正确构建数组包含判断的条件 ConditionalOperators.Cond condOperation = ConditionalOperators.when( AggregationExpressions.in(userId, "$lstLikeUserid") ) .then("true") .otherwise("false"); ProjectionOperation projectOperation = Aggregation.project() .and(condOperation).as("like") .andInclude("title"); Aggregation aggregation = Aggregation.newAggregation(projectOperation); AggregationResults<ChannelItemEntry> result = mongoTemplate .aggregate(aggregation, ChannelItemEntry.class, ChannelItemEntry.class);
另一种可选写法:用$indexOfArray判断
如果你偏好使用$indexOfArray操作符(它会返回元素在数组中的索引,不存在则返回-1),也可以这样编写条件:
ConditionalOperators.Cond condOperation = ConditionalOperators.when( AggregationExpressions.compareValueOf("$lstLikeUserid") .indexOf(userId) .greaterThanEqualTo(0) ) .then("true") .otherwise("false");
这两种写法都能准确判断目标用户ID是否存在于lstLikeUserid数组中,让"like"字段返回正确的结果。
内容的提问来源于stack exchange,提问作者philippe vandenhove
相关产品推荐
相关产品推荐

