mongodb - 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"));
}
});
感谢瓦尔曼的帮助!
解决方案
推荐阅读
- python - upserting sqlite 失败并出现语法错误
- authentication - 在 Google 上进行应用审核时需要测试登录
- vhdl - 如何在 VHDL 中获得具有 n 个 '1' 的二进制数?
- c# - 为什么在 WPF 中删除 StartupUri 时不应用样式?
- php - PHP 根据不同的数组元素用预定义的值填充缺失的数组元素
- systemd - 使用 autotools 安装 systemd 服务
- string - 清理坏的 UTF-8 字符串
- mongodb - MongoDB:只保留第一个日期
- java - 在 Quarkus 应用程序中需要 resteasy 吗?
- javascript - jquery Datatable 操作导致整个页面重新加载