2017-06-18 88 views
0

的$ COND我有一个文档集合像下面如何使用SPEL表示蒙戈

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

我想STAT与segmentedStatus = 1多少文件,

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

春天数据蒙戈

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

,但我觉得上面的方法有些麻烦所以想知道,如果在这种情况下,可以使用SPEL,我试过以下方式

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

但它抛出异常

Exception in thread "main" java.lang.IllegalArgumentException: Unsupported Element: [email protected]3d Type: class org.springframework.data.mongodb.core.spel.ExpressionNode You probably have a syntax error in your SpEL expression! 
+0

[如何使用Spring的MongoDB的聚合框架$ COND操作(HTTPS的可能重复:// stackoverflow.com/questions/29186185/how-to-use-cond-operation-in-spring-mongodb-aggregation-framework) – chridam

回答

2

$cond速记三元操作的语法是目前不支持。你仍然可以通过cond(if, then, else)

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

引用$cond运营商,这将创建以下文件:

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