0

I found this: Handle division by zero in mongoDB useful if I were using mongoDB directly, to resolve division by zero issue, but I couldn't found a way of doing this with Morphia.

What I need to accomplish is exactly what the refered question says, but using Morphia, that's why I don't show further code examples. Anyone could give me a tip of how can I do a division with morphia aggregation projection and returns 0 result in cases where divisor is zero?

Community
  • 1
  • 1
Daniel Ardison
  • 502
  • 4
  • 18

1 Answers1

1

You can try to use Projection class for that purpose.

import static org.mongodb.morphia.aggregation.Projection.divide;
import static org.mongodb.morphia.aggregation.Projection.expression;
import static org.mongodb.morphia.aggregation.Projection.projection;    
...
final AggregationPipeline pipeline = datastore.createAggregation(ItemEntity.class)
                .project(projection("_id").suppress(),
                        projection("name", "name"),
                        projection("upvotes", "upvotes"),
                        projection("downvotes", "downvotes"), 
                        projection("quality", expression("$cond", expression(FilterOperator.EQUAL.val(), projection("downvotes"), 0), projection("upvotes"), divide(projection("upvotes"), projection("downvotes"))))
                )
                .sort(Sort.descending("quality"));
EugeneL
  • 9
  • 1