gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:15:28 26 4
gpt4 key购买 nike

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

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

在 mongo shell 中运行良好。如何使用 Spring-Mongodb 中的聚合框架来表达这一点?我见过 ProjectionOperationBuilder、ExpressionProjectionOperationBuilder 类型,但没有看到如何使用它们的示例……有什么建议吗?

最佳答案

如果使用支持 $cond 的当前 Spring Data 版本 运算符通过 $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 的接口(interface):

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);

关于spring - Spring-MongoDb聚合框架中如何使用$cond操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29186185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com