KSCOLD LogoKSCOLD
Blog
Feed
Product
Admin Night
Vault
Guestbook
Info

Vault 목록

집계(Aggregation)

연결된 노트와 함께 읽기

집계(Aggregation)

2026년 5월 17일
  • MongoDB 집계(Aggregation)는 여러 단계의 파이프라인(Pipeline)을 통해 도큐먼트를 변환·그룹화·분석하는 기능이다.
  • SQL의 GROUP BY, JOIN, HAVING, 집계 함수(SUM, COUNT 등)에 해당한다.
  • Spring Data MongoDB에서는 MongoTemplate의 Aggregation 클래스 또는 MongoDB Shell의 aggregate() 명령어로 사용한다.

파이프라인 구조

Mermaid스크롤로 확대 · 드래그로 이동
  • 각 단계의 출력이 다음 단계의 입력이 된다.
  • 필요한 단계만 조합해서 사용한다.

주요 파이프라인 스테이지

스테이지SQL 대응설명
$matchWHERE조건으로 도큐먼트 필터링
$groupGROUP BY필드 기준 그룹화 + 집계 함수
$projectSELECT반환할 필드 지정/변환
$sortORDER BY정렬
$limitLIMIT결과 수 제한
$skipOFFSET결과 건너뛰기
$lookupJOIN다른 컬렉션과 조인
$unwind-배열을 개별 도큐먼트로 펼치기
$addFieldsSELECT ... AS새 필드 추가

집계 함수

함수설명
$sum합계
$avg평균
$min / $max최솟값 / 최댓값
$count도큐먼트 수 ({ $sum: 1 } 로도 사용)
$push값들을 배열로 수집
$first / $last그룹 내 첫 번째/마지막 값

MongoDB Shell 예시

JavaScript

Spring MongoTemplate 사용

Java

$lookup (다른 컬렉션 조인)

JavaScript

관련

  • MongoDB
  • MongoTemplate
  • Spring Data MongoDB
  • GROUP

Synapse Map Insight

// 카테고리별 게시글 수와 평균 조회수 집계 db.posts.aggregate([ { $match: { status: "published" } }, // 공개된 글만 { $group: { _id: "$category", postCount: { $sum: 1 }, avgViews: { $avg: "$viewCount" } }}, { $sort: { postCount: -1 } }, // 글 수 내림차순 { $limit: 10 } ])
Aggregation agg = Aggregation.newAggregation( Aggregation.match(Criteria.where("status").is("published")), Aggregation.group("category") .count().as("postCount") .avg("viewCount").as("avgViews"), Aggregation.sort(Sort.Direction.DESC, "postCount"), Aggregation.limit(10) ); AggregationResults<CategoryStats> results = mongoTemplate.aggregate(agg, "posts", CategoryStats.class); List<CategoryStats> stats = results.getMappedResults();
// posts 컬렉션에 authors 컬렉션을 조인 db.posts.aggregate([ { $lookup: { from: "authors", localField: "authorId", foreignField: "_id", as: "authorInfo" }}, { $unwind: "$authorInfo" } ])