Reputation: 21
How can I add condition on my projection stage during aggregation using Spring Data?
For example I want to add new_field
that will be calculated by formula field1 / field2
. From Code side it would look like:
ProjectionOperation projectionOperation = project("field1", "field2").andExpression("field1 / field2").as("field3");
But if field2
is equal to 0
, I'll get an error. So to avoid such situation it was suggested to use $cond
operator but I have no idea how it should look like in code. Do anybody have any thoughts?
Note. Expression field2 != 0 ? 1 : 0
didn't work (even if "SpEL" allows such syntax).
Upvotes: 2
Views: 3359
Reputation: 385
You can find more examples here: https://www.javatips.net/api/spring-data-mongodb-master/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperationUnitTests.java
Upvotes: 0
Reputation: 21
It's a little late but for future viewers of this question, the following code worked for me. It returns 0 as the value of field3 when field2 is 0.
ProjectionOperation projectionOperation = Aggregation.project("field1, field2")
.and(AggregationSpELExpression.expressionOf("cond(field2 == 0, 0, field1/field2)"))
.as("field3");
Upvotes: 2
Reputation: 13
I just had the same issue. != does not seem to be supported, however you can use "ifNull" or "cond" in your SPeL.
See here: how to use spel to represent $cond of mongo
And here for more examples: https://github.com/spring-projects/spring-data-mongodb/blob/master/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformerUnitTests.java
Upvotes: 1