Aggregation
MongoDB의 aggregation은 데이터를 처리하고 변환하기 위한 강력한 도구입니다.
Aggregation 파이프라인은 여러 단계의 데이터 처리 단계를 포함하며, 각 단계는 데이터를 조작하고 변환하여 원하는 결과를 생성합니다. 즉 위에서부터 각 단계마다 입력한 Operators에 따라 데이터가 처리되고 처리 된 데이터가 다음 단계로 넘어간다는 것입니다.
Aggregation은 SQL의 GROUP BY와 유사한 작업을 수행할 수 있으며, 데이터의 그룹화, 정렬, 필터링, 변환, 계산 등 다양한 작업을 지원합니다.
https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/
Aggregation Stages — MongoDB Manual
Docs Home → MongoDB Manual In the db.collection.aggregate() method and db.aggregate() method, pipeline stages appear in an array. In the Atlas UI, you can arrange pipeline stages using the aggregation pipeline builder. Documents pass through the stages i
www.mongodb.com
https://www.mongodb.com/docs/manual/reference/operator/aggregation/
Aggregation Operators — MongoDB Manual
Docs Home → MongoDB Manual The aggregation pipeline operators are compatible with MongoDB Atlas and on-premise environments.For details on a specific operator, including syntax and examples, click on the link to the operator's reference page.You can use
www.mongodb.com
Aggregation Stage
Aggregation Stage 수집된 데이터를 통합하고 집계합니다.
형태
db.collection.aggregate([ { <stage> }, ... ])
예시 1) 서울에 거주하는 사용자들 중, 직업 사람들의 총 급여 출력
db.users.aggregate([ { $match: { region: "seoul" } }, { $group: { _id: { $getField: "job" }, totalSalary: { $sum: "$salary" } } } ])
- $match: 해당 조건에 맞는 document만을 선택합니다. 예시에서는 'region' 필드가 'seoul'인 document만을 선택합니다.
- $group: document들을 그룹화하고, 각 그룹별로 특정 필드를 기준으로 데이터를 집계합니다. 예시에서는 'job' 필드를 기준으로 그룹화하고, 각 그룹내의 'salary'값을 모두 합하여 'totalSalary'필드로 출력하였습니다.
- $getField: 집계 표현식 중 하나로, 지정된 필드의 값을 가져옵니다. { $getField: "salary" } 를 "$salary"로 축약하여 나타낼 수 있습니다.
예시2) 직업 별 사용자 이름을 배열에 넣어 출력
db.users.aggregate([ { $group: { _id: "$job", names: { $push: "$name" } } } ])
- 만약 사용자 이름을 넣어주는게 아니라 document를 넣어주고 싶다면 "$$ROOT"라 작성하면 됩니다.
예시3) 2023년 1월1일 부터 2024년 1월 30일까지 일마다 사람들이 지출한 금액의 평균을 내림차순으로 출력
db.users.aggregate([ { $match: { date: { $gte: new ISODate("2023-01-01"), $lt: new ISODate("2024-01-30") } } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" }, }, averageExpenditure: { $avg: "$expenditure" } } }, { $sort: { averageExpenditure: -1 } } ])
'DBMS > MongoDB' 카테고리의 다른 글
MongoDB 배열 다루는 문법 (1) | 2024.01.30 |
---|---|
MongoDB MQL(MongoDB Query Language) (0) | 2024.01.30 |
MongoDB MongoDB 배포 형태: Replica Set & Sharded Cluster (0) | 2024.01.25 |
MongoDB MongoDB: 문서 지향 NoSQL (0) | 2024.01.23 |