Spring数据MongoDB在投影中的条件

问题描述 投票:1回答:2

如何在使用Spring Data进行聚合期间在投影阶段添加条件?

例如,我想添加将由公式new_field计算的field1 / field2。从代码方面看起来像:

ProjectionOperation projectionOperation = project("field1", "field2").andExpression("field1 / field2").as("field3");

但如果field2等于0,我会收到错误。所以为了避免这种情况,建议使用$cond运算符,但我不知道它在代码中应该是什么样子。有人有什么想法吗?

注意。表达式field2 != 0 ? 1 : 0不起作用(即使“SpEL”允许这样的语法)。

spring-data spring-data-mongodb
2个回答
1
投票

我刚才有同样的问题。 !=似乎不受支持,但您可以在SPeL中使用“ifNull”或“c​​ond”。

见这里:how to use spel to represent $cond of mongo

这里有更多例子:https://github.com/spring-projects/spring-data-mongodb/blob/master/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformerUnitTests.java


0
投票

这有点晚了但是对于这个问题的未来观众,以下代码对我有用。当field2为0时,它返回0作为field3的值。

ProjectionOperation projectionOperation = Aggregation.project("field1, field2")
                .and(AggregationSpELExpression.expressionOf("cond(field2 == 0, 0, field1/field2)"))
                .as("field3");
© www.soinside.com 2019 - 2024. All rights reserved.