Aggregation Framework

Hanbyul·2023년 11월 16일

Java

목록 보기
2/23

MongoDB의 Aggregation Framework는 데이터 처리 파이프라인을 제공함. 이 파이프라인을 통해 데이터를 변환하고 조합하여 복잡한 질의를 수행할 수 있음.

Aggregation Framework는 다양한 스테이지를 통해 데이터를 처리. 각 스테이지는 독립적이며, 각 스테이지의 출력은 다음 스테이지의 입력으로 사용됨.

주요 스테이지로는 $match, $group, $sort, $project 등이 있음.

  1. $match: 쿼리 조건과 일치하는 문서만 다음 스테이지로 전달. 일종의 필터 역할.
  2. $group: 입력 문서를 주어진 표현식에 따라 그룹화.
  3. $sort: 입력 문서를 주어진 기준에 따라 정렬.
  4. $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 }
]
profile
공부공부

0개의 댓글