Search code examples
spring-data-mongodbspring-el

how to use spel to represent $cond of mongo


I have a collection with documents like below

{
    "_id" : ObjectId("5946360fdab24b1d05fac7e6"),
    "name" : "aaa",
    "createdAt" : NumberLong("1497773583563"),
    "segmentedStatus" : 0
}

I want to stat how many documents with segmentedStatus = 1,

db.foo.aggregate(
    {$project: {_id:0, segmentedCount:{$cond: [{$eq:["$segmentedStatus",1]}, 1, 0]} } },
    {$group: {_id:null, count:{$sum:"$segmentedCount"}}}
)

In spring data mongo

Aggregation aggregation = newAggregation(project().and("segmentedCount").applyCondition(when(where("segmentedStatus").is(1)).then(1).otherwise(0)),
        group().sum("segmentedCount").as("count")
);

but I feel above manner a little cumbersome so want to know if could use spel in this case , I tried below manner

Aggregation aggregation = newAggregation(project().andExpression("segmentedStatus == 1 ? 1 : 0").as("segmentedCount"),
        group().sum("segmentedCount").as("count")
);

but it throws exception

Exception in thread "main" java.lang.IllegalArgumentException: Unsupported Element: org.springframework.data.mongodb.core.spel.ExpressionNode@4d5d943d Type: class org.springframework.data.mongodb.core.spel.ExpressionNode You probably have a syntax error in your SpEL expression!

Solution

  • The short hand ternary operator syntax for $cond is currently not supported. Still you can reference the $cond operator via cond(if, then, else)

    project()
      .and(AggregationSpELExpression.expressionOf("cond(segmentedStatus == 1, 1, 0)"))
      .grou...
    

    which will create the following:

    { "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }