我有一个包含以下文件的集合
{
"_id" : ObjectId("5946360fdab24b1d05fac7e6"),
"name" : "aaa",
"createdAt" : NumberLong("1497773583563"),
"segmentedStatus" : 0
}
我想用segmentedStatus = 1来判断有多少文档,
db.foo.aggregate(
{$project: {_id:0, segmentedCount:{$cond: [{$eq:["$segmentedStatus",1]}, 1, 0]} } },
{$group: {_id:null, count:{$sum:"$segmentedCount"}}}
)
在spring data mongo中
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: 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!
答案 0 :(得分:2)
目前不支持$cond
的简写三元运算符语法。您仍然可以通过$cond
cond(if, then, else)
运算符
project()
.and(AggregationSpELExpression.expressionOf("cond(segmentedStatus == 1, 1, 0)"))
.grou...
将创建以下内容:
{ "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }