一尘不染

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

spring

我有一个聚合管道,其中包括一个像这样的项目:

$project: {
  start: {
    $cond: {
      if: {
        $eq: ["$start", "EARLY"]
      },
      then: "$deltastart.start",
      else: "$deltastart.end"
    }
  },...
},...

在mongo shell中可以正常工作。如何在Spring-Mongodb中使用Aggregation框架表达这一点?我见过ProjectionOperationBuilder,ExpressionProjectionOperationBuilder类型,但没有一个示例如何使用它们……有什么建议吗?


阅读 2078

收藏
2020-04-19

共1个答案

一尘不染

如果使用$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); 
2020-04-19