mongotemplate聚合查询
时间: 2023-08-07 11:01:53 浏览: 122
您好!对于MongoTemplate的聚合查询,您可以使用Aggregation类来构建聚合查询管道。以下是一个简单的示例:
```java
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
public class AggregationExample {
private MongoTemplate mongoTemplate;
public AggregationExample(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public void performAggregation() {
TypedAggregation aggregation = newAggregation(
// 添加聚合操作
match(Criteria.where("fieldName").is("value")),
group("groupField").count().as("count"),
sort(Sort.Direction.DESC, "count")
);
AggregationResults<AggregateResultClass> results = mongoTemplate.aggregate(aggregation, "collectionName", AggregateResultClass.class);
List<AggregateResultClass> resultList = results.getMappedResults();
// 处理结果
for (AggregateResultClass result : resultList) {
// 进行相应的操作
// result.getGroupField();
// result.getCount();
}
}
}
// 聚合结果的POJO类
class AggregateResultClass {
private String groupField;
private int count;
// 省略构造函数、getter和setter
}
```
请根据您的具体需求修改上述示例中的字段和条件。希望对您有所帮助!如果您有任何其他问题,请随时提问。
阅读全文