如何在Spring-MongoDb聚合框架中使用$ cond *** 作

如何在Spring-MongoDb聚合框架中使用$ cond *** 作,第1张

如何在Spring-MongoDb聚合框架中使用$ cond *** 作

如果使用

$cond
通过
$project
管道支持 *** 作员的当前Spring Data版本,则可以将其转换为(未测试):

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;import static org.springframework.data.mongodb.core.aggregation.ConditionalOperators.Cond.*;import org.springframework.data.mongodb.core.query.Criteria;Cond condOperation = ConditionalOperators.when(Criteria.where("start").is("EARLY"))   .thenValueOf("deltastart.start")   .otherwise("deltastart.end");Aggregation agg = newAggregation(project().and(condOperation).as("start"));AggregationResults<MyClass> results = mongoTemplate.aggregate(agg, MyClass.class); List<MyClass> myList = results.getMappedResults();

对于

$cond
在聚合 *** 作中不支持运算符的Spring-Data MongoDB版本,有一种解决方法是实现AggregationOperation接口以接收DBObject:

public class CustomProjectAggregationOperation implements AggregationOperation {    private DBObject operation;    public CustomProjectAggregationOperation (DBObject operation) {        this.operation = operation;    }    @Override    public DBObject toDBObject(AggregationOperationContext context) {        return context.getMappedObject(operation);    }}

然后

$project
,在聚合管道中将 *** 作实现为DBObject,该 *** 作与你拥有的 *** 作相同:

DBObject operation = (DBObject) new BasicDBObject(    "$project", new BasicDBObject(         "start", new BasicDBObject(     "$cond", new Object[]{  new BasicDBObject(      "$eq", new Object[]{ "$start", "EARLY"}  ),  "$deltastart.start",  "$deltastart.end"      })     ));

然后可以在TypeAggregation中使用它:

TypedAggregation<CustomClass> aggregation = newAggregation(CustomClass.class,    new CustomProjectAggregationOperation(operation));AggregationResults<CustomClass> result = mongoTemplate.aggregate(aggregation, CustomClass.class); 


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5110088.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存