【发布时间】:2021-06-15 11:36:30
【问题描述】:
我是 Spring 和 Mongo 的新手。我正在使用 Spring Batch 获取一些报告。我的查询需要一些 MongoItemReader 不支持的聚合,所以我按照下面的 stackoverflow 链接扩展了该类。
How to use Aggregation Query with MongoItemReader in spring batch
但是我的聚合有问题。我制作了在 mongoDB 中运行良好但无法将其转换为 Spring mongo 聚合的聚合。
MongoDb 聚合按预期工作。
db.getCollection('orders').aggregate([
{$match: {orderDate: {$gt:"2021-03-15",$lt: "2021-03-17"}, "status" :{"$in": ["GREEN", "YELLOW"]}}},
{$group: {_id: {orderDate: "$orderDate", node: "$node", code1:"$code1", code2:"$code2"}, orderUnts: {$sum: 1}}},
{"$project": {orderDate:"$_id.orderDate", node:"$_id.node", code1:"$_id.code1", code2:"$_id.code2", orderUnts:"$orderUnts"}}
])
Spring Mongo 聚合导致错误。
String[] fields = {"orderDate", "node", "code1", "code2"};
String[] projectionFields = {"orderDate", "orderDate", "code1", "code2"};
MatchOperation matchOp = Aggregation.match(Criteria.where("orderDate").gt(startDate).and("orderDate").lt(endDate).and("status").in("GREEN", "YELLOW"));
GroupOperation groupOp = Aggregation.group(fields).sum("orderUnts").as("_id");
ProjectionOperation projectOp = Aggregation.project(projectionFields);
SortOperation sortOp = Aggregation.sort(Sort.by(Sort.Direction.ASC, "orderDate"));
Aggregation aggregation = Aggregation.newAggregation(matchOp, groupOp, projectOp, sortOp);
我遇到了唯一字段错误。
Caused by: java.lang.IllegalStateException: An implementation of MongoOperations is required.
at org.springframework.util.Assert.state(Assert.java:76)
at org.springframework.batch.item.data.MongoItemReader.afterPropertiesSet(MongoItemReader.java:238)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1847)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1784)
... 81 common frames omitted
MongoItemReader 扩展类。
@Data
public class CustomMongoItemReader<T> extends MongoItemReader<T> {
private MongoTemplate template;
private Class<? extends T> type;
private String collection;
private MatchOperation matchOperation;
private GroupOperation groupOperation;
private ProjectionOperation projectionOperation;
private SortOperation sortOperation;
private Aggregation aggregation;
@Override
protected Iterator<T> doPageRead() {
Pageable page = PageRequest.of(this.page, this.pageSize);
if(matchOperation != null && groupOperation != null) {
Aggregation agg = Aggregation.newAggregation(matchOperation,
groupOperation,
projectionOperation,
sortOperation,
Aggregation.skip(Long.valueOf(page.getPageNumber() * page.getPageSize())),
Aggregation.limit(page.getPageSize())
);
return (Iterator<T>) template.aggregate(agg, collection, this.type).iterator();
}
else {
return Collections.emptyIterator();
}
}
}
如果问题需要更多信息,请告诉我。提前致谢。
【问题讨论】:
-
我添加了一个答案。有帮助吗?请查看:stackoverflow.com/help/someone-answers.
标签: mongodb spring-boot aggregation-framework spring-batch