Reed
Reed

Reputation: 21

Spring data MongoDB condition in projection

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

Answers (3)

Pratish Bhatnagar
Pratish Bhatnagar

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

stba
stba

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

Related Questions