Hvis du bruger den aktuelle Spring Data-udgivelse, som understøtter $cond
operatør via $project
pipeline, så kan denne konverteres til (utestet):
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();
Til Spring-Data MongoDB-version, som ikke understøtter $cond
operatør i aggregeringsoperationen, er der en løsning, som er at implementere AggregationOperation grænseflade til at tage i et DBO-objekt:
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);
}
}
Implementer derefter $project
drift som et DBO-objekt i aggregeringspipelinen, der er den samme som den, du har:
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"
}
)
)
);
som du så kan bruge i TypeAggregation:
TypedAggregation<CustomClass> aggregation = newAggregation(CustomClass.class,
new CustomProjectAggregationOperation(operation)
);
AggregationResults<CustomClass> result = mongoTemplate.aggregate(aggregation, CustomClass.class);