如何使用 spel 表示 mongo 的 $cond
how to use spel to represent $cond of mongo
我收集了如下文件
{
"_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数据中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!
目前不支持 $cond
的简写三元运算符语法。您仍然可以通过 cond(if, then, else)
引用 $cond
运算符
project()
.and(AggregationSpELExpression.expressionOf("cond(segmentedStatus == 1, 1, 0)"))
.grou...
这将创建以下内容:
{ "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }
我收集了如下文件
{
"_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数据中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!
目前不支持 $cond
的简写三元运算符语法。您仍然可以通过 cond(if, then, else)
$cond
运算符
project()
.and(AggregationSpELExpression.expressionOf("cond(segmentedStatus == 1, 1, 0)"))
.grou...
这将创建以下内容:
{ "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }