MongoDB Spring Data聚合操作中如何对字段值进行取反?
解决方案
你可以直接使用Spring Data MongoDB提供的算术运算工具类ArithmeticOperators.Multiply,将转换后的Double值乘以-1即可实现取反,修改后的代码如下:
// 需提前导入算术运算工具类 import org.springframework.data.mongodb.core.aggregation.ArithmeticOperators; // 修改后的条件逻辑 Cond cond1 = ConditionalOperators.when(Criteria.where("status").is("inactive")) .thenValueOf("cost") // 对转换后的结果做乘-1操作实现取反 .otherwise(ArithmeticOperators.Multiply.valueOf( ConvertOperators.valueOf(ConditionalOperators.ifNull("cost").then(0)).convertToDouble() ).multiplyBy(-1)); AggregationOperation project = Aggregation.project() .and(cond1).as("cost") .and("timeStamp").as("timeStamp") .and("name").as("name") .and("status").as("status");
逻辑说明
- 原有
ConvertOperators的执行逻辑保持不变,先处理cost为null的情况默认赋值为0,再转换为Double类型 - 套入
Multiply运算后,会将转换后的结果乘以-1得到负值,即使原cost为null时返回的0取反后还是0,符合预期 - 如果你更习惯用减法实现取反,也可以替换为
ArithmeticOperators.Subtract.valueOf(0).subtract(转换后的结果),效果完全一致
内容的提问来源于stack exchange,提问作者jymez
相关产品推荐
相关产品推荐

