如果使用
$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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)