MongoDB의 Aggregation Framework는 데이터 처리 파이프라인을 제공함. 이 파이프라인을 통해 데이터를 변환하고 조합하여 복잡한 질의를 수행할 수 있음.
Aggregation Framework는 다양한 스테이지를 통해 데이터를 처리. 각 스테이지는 독립적이며, 각 스테이지의 출력은 다음 스테이지의 입력으로 사용됨.
주요 스테이지로는 $match, $group, $sort, $project 등이 있음.
ex.
json
[
{ "_id": 1, "name": "Kim", "age": 20, "salary": 2000 },
{ "_id": 2, "name": "Lee", "age": 20, "salary": 3000 },
{ "_id": 3, "name": "Park", "age": 30, "salary": 4000 },
{ "_id": 4, "name": "Choi", "age": 30, "salary": 5000 }
]
이 데이터에 대해 Aggregation Framework를 사용하여
연령별 평균 급여를 계산하려면 다음과 같이 작성할 수 있음
java
Aggregation agg = Aggregation.newAggregation(
Aggregation.group("age").avg("salary").as("averageSalary"),
Aggregation.project("averageSalary").and("_id").as("age")
);
AggregationResults<Document> results = mongoTemplate.aggregate(agg, "collectionName", Document.class);
'age' 필드를 기준으로 그룹화한 후, 각 그룹의 'salary' 필드의
평균을 계산하여 'averageSalary'라는 새로운 필드에 저장.
'averageSalary'와 '_id' 필드를 선택하여 결과 문서를 생성
결과
[
{ "_id": 20, "averageSalary": 2500 },
{ "_id": 30, "averageSalary": 4500 }
]