如果使用当前Spring Data版本并且支持通过$cond
操作符的$project
管道,那么可以将其转换为(未经测试):
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)
DBObjectAggregationOperation
类的实现吗? - Half Blood PrinceCustomProjectAggregationOperation
,我已经改正了。 - chridamAggregationOperation
在spring-data-mongodb-2.0.8.RELEASE
版本中不再公开toDBObject
方法。 - Always Learning