org.springframework.data.mongodb.core.aggregation.Aggregation
是 Spring Data MongoDB 中用于构建 MongoDB 聚合管道的一个类。它允许你以声明性的方式定义聚合的各个阶段,如 $match
、$group
、$sort
、$project
等。
下面我将解释如何使用 Aggregation
类及其相关方法:
1. 引入依赖
首先,确保你的项目中包含了 Spring Data MongoDB 的相关依赖。
2. 创建 Aggregation 对象
使用 Aggregation
的静态方法开始创建一个聚合查询。
Aggregation aggregation = Aggregation.newAggregation(
// 聚合阶段...
);
3. 聚合阶段方法
以下是一些常用的聚合阶段方法:
Aggregation.match(Criteria criteria)
: 添加一个$match
阶段,用于过滤文档。Aggregation.group(String... fields).first(String fieldName).as(String resultFieldName)
: 添加一个$group
阶段,并按指定字段进行分组。这里使用了first
累加器作为示例,但还有sum
、avg
、max
、min
等其他累加器。Aggregation.sort(Sort sort)
: 添加一个$sort
阶段,用于对文档进行排序。Aggregation.project(String... fieldsToAdd)
: 添加一个$project
阶段,用于指定输出文档的字段。Aggregation.lookup(String fromCollection, String localField, String foreignField, String asField)
: 添加一个$lookup
阶段,用于执行左外连接。- … 以及其他更多的聚合阶段方法。
4. 示例
下面是一个完整的示例,演示如何使用 Aggregation
类来执行一个包含 $match
、$group
和 $sort
阶段的聚合查询:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MyService {
@Autowired
private MongoTemplate mongoTemplate;
public List<MyAggregationResult> aggregateExample() {
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("status").is("ACTIVE")), // 匹配状态为 ACTIVE 的文档
Aggregation.group("category") // 按 category 字段分组
.sum("price").as("totalPrice") // 计算每个组的 price 字段的总和
.first("name").as("firstProductName"), // 获取每个组的第一个文档的 name 字段值
Aggregation.sort(Sort.Direction.DESC, "totalPrice") // 按 totalPrice 字段降序排序
);
AggregationResults<MyAggregationResult> results = mongoTemplate.aggregate(
aggregation,
"yourCollectionName", // 你的集合名称
MyAggregationResult.class // 映射结果的类
);
return results.getMappedResults(); // 返回结果列表
}
// 定义你的结果类
public static class MyAggregationResult {
private String category;
private Double totalPrice;
private String firstProductName;
// getters, setters, toString...
}
}
5. 执行聚合查询
使用 MongoTemplate
的 aggregate()
方法来执行聚合查询。你需要传入 Aggregation
对象、集合名称以及结果映射的类。
6. 注意事项
- 确保你的 MongoDB 集合名称和字段名称与你的代码中的名称相匹配。
- 根据需要调整聚合阶段和累加器的使用。
- 如果你的聚合查询很复杂,考虑使用 MongoDB 的聚合框架直接在 MongoDB shell 中测试它,以确保逻辑正确。