首页 > 解决方案 > springboot如何实现MongoDB聚合查询管道stage { $group: {_id: "$$ROOT"} }?

问题描述

在我的 spring-boot 项目中,MongoDB 聚合查询是使用 org.springframework.data.mongodb.core.aggregation 包中的不同接口定制的,如 AggregationOperation、GroupOperation 等,如下所示。

List<AggregationOperation> aggList = new ArrayList<>();

MatchOperation match = match(//pass filters here...
aggList.add(match);

GroupOperation group = new GroupOperation(...//group fields and aliases
aggList.add(group);

ProjectionOperation projection= project().andExclude("_id");
//append other projections here
...
aggList.add(projection);

Aggregation aggregationOp = Aggregation.newAggregation(aggList);
AggregationResults<Object> aggResults = this.getOperations().aggregate(aggregationOp , collectionName,
                Object.class);
return aggResults.getMappedResults();

到目前为止,这运作良好。但是现在我需要添加一个具有 $$ROOT 阶段的组(为了消除重复),如下所示。

{ $group: { _id: "$$ROOT" } }

我尝试了不同的方法但失败了。下面给出了失败的方法。

//Approach 1:
aggList.add(Aggregation.group(Aggregation.ROOT));

这给了我以下错误,

java.lang.IllegalArgumentException: Invalid reference '$$ROOT'!
    at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:100) ~[spring-data-mongodb-2.1.2.RELEASE.jar:2.1.2.RELEASE]

和方法2,

//Approach 2:
aggList.add(new AggregationOperation() {

                    @Override
                    public Document toDocument(AggregationOperationContext context) {
                        return new Document("$group", 
                                new Document("_id", Aggregation.ROOT));
                    }
                });

这给了我以下错误,

java.lang.IllegalArgumentException: Invalid reference '_id'!
    at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:100) ~[spring-data-mongodb-2.1.2.RELEASE.jar:2.1.2.RELEASE]

谁能帮我吗?

答案: 下面的代码有效!

aggList.add(new AggregationOperation() {

                    @Override
                    public Document toDocument(AggregationOperationContext context) {
                        return new Document("$group", 
                                new Document("_id", "$$ROOT"));
                    }
                });

感谢瓦尔曼的帮助!

标签: mongodbspring-bootaggregation-framework

解决方案


推荐阅读