如何使用spel来表示mongo的$cond [英] how to use spel to represent $cond of mongo
本文介绍了如何使用spel来表示mongo的$cond的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含如下文档的集合
I have a collection with documents like below
{
"_id" : ObjectId("5946360fdab24b1d05fac7e6"),
"name" : "aaa",
"createdAt" : NumberLong("1497773583563"),
"segmentedStatus" : 0
}
我想统计有多少个文档,segmentedStatus = 1,
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"}}}
)
在春季数据 mongo
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")
);
但它抛出异常
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!
推荐答案
当前不支持 $cond
的简写三元运算符语法.您仍然可以通过 cond(if, then, else)
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...
这将创建以下内容:
{ "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }
这篇关于如何使用spel来表示mongo的$cond的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文