stack-analysis
CHAPTER 43 / 90
읽기 약 2분
FUNCTION
MongoDB Aggregation Pipeline 실전
핵심 개념
$match·$group·$lookup·$facet — 통계·검색·분석 쿼리 작성.
본문
기본 파이프라인
db.orders.aggregate([
// 1. 필터
{ $match: {
status: 'completed',
createdAt: { $gte: ISODate('2026-01-01') }
}},
// 2. 그룹 + 집계
{ $group: {
_id: { year: { $year: '$createdAt' }, month: { $month: '$createdAt' } },
total: { $sum: '$amount' },
count: { $sum: 1 },
avg: { $avg: '$amount' },
}},
// 3. 정렬
{ $sort: { '_id.year': -1, '_id.month': -1 } },
// 4. 형태 변환
{ $project: {
_id: 0,
period: { $concat: [
{ $toString: '$_id.year' }, '-',
{ $toString: '$_id.month' }
]},
total: 1, count: 1,
avg: { $round: ['$avg', 2] },
}},
]);$lookup (Join)
// 주문 + 사용자 정보
db.orders.aggregate([
{ $lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'user'
}},
{ $unwind: '$user' }, // 배열 → 객체
{ $project: {
orderId: '$_id',
amount: 1,
'user.name': 1,
'user.email': 1,
}}
]);
// 다단계 join
db.orders.aggregate([
{ $lookup: {
from: 'orderItems',
localField: '_id',
foreignField: 'orderId',
as: 'items',
pipeline: [ // 서브 파이프라인
{ $lookup: {
from: 'products',
localField: 'productId',
foreignField: '_id',
as: 'product'
}},
{ $unwind: '$product' },
]
}},
]);$facet (한 번에 여러 집계)
// 대시보드 — 여러 집계 한 번에
db.orders.aggregate([
{ $match: { createdAt: { $gte: thirtyDaysAgo } } },
{ $facet: {
// 일별 매출
byDay: [
{ $group: {
_id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
total: { $sum: '$amount' }
}},
{ $sort: { _id: 1 } }
],
// 카테고리별
byCategory: [
{ $unwind: '$items' },
{ $group: {
_id: '$items.category',
total: { $sum: '$items.subtotal' }
}}
],
// 전체 통계
overall: [
{ $group: {
_id: null,
count: { $sum: 1 },
total: { $sum: '$amount' },
avg: { $avg: '$amount' }
}}
]
}}
]);텍스트 검색
// 텍스트 인덱스
db.products.createIndex({ name: 'text', description: 'text' });
db.products.aggregate([
{ $match: { $text: { $search: '리액트 타입스크립트' } } },
{ $addFields: { score: { $meta: 'textScore' } } },
{ $sort: { score: { $meta: 'textScore' } } },
{ $limit: 20 }
]);배열 필드 처리
// $size, $filter, $map
db.users.aggregate([
{ $project: {
name: 1,
activePosts: {
$filter: {
input: '$posts',
as: 'post',
cond: { $eq: ['$$post.published', true] }
}
},
postCount: { $size: '$posts' },
titles: { $map: { input: '$posts', as: 'p', in: '$$p.title' } }
}}
]);$bucket — 히스토그램
db.orders.aggregate([
{ $bucket: {
groupBy: '$amount',
boundaries: [0, 10000, 50000, 100000, 500000],
default: '500000+',
output: {
count: { $sum: 1 },
avg: { $avg: '$amount' }
}
}}
]);
// 결과
[
{ _id: 0, count: 234, avg: 5234 },
{ _id: 10000, count: 567, avg: 32100 },
{ _id: 50000, count: 123, avg: 78900 },
{ _id: '500000+', count: 12, avg: 1234567 },
]성능 — 인덱스 + 단계 순서
파이프라인 첫 단계 = $match (인덱스 활용)
→ 데이터를 줄인 후 $group, $lookup
❌ $unwind 먼저 → 폭증
✅ $match 먼저 → 적은 데이터로 처리
// EXPLAIN
db.orders.aggregate(pipeline, { explain: true });다음 챕터
CH.44 "Supabase Edge Functions + Realtime".
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내 코드의 MongoDB Aggregation 부분을 분석해서 실전 분석 + 개선 우선순위를 알려줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
MongoDB Aggregation 관련 인기 라이브러리/패턴 5개를 비교 분석해서 패턴 추출를 알려줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 프로젝트 전체에서 MongoDB Aggregation 최적화 가능 위치를 보고해줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 한국 백엔드 시장의 MongoDB Aggregation 트렌드를 솔직히 알려줘.
⭐ 이것만 기억하세요
MongoDB Aggregation Pipeline 실전은 이 3가지만 확실히 잡으세요
1.Aggregation = SQL의 GROUP BY + JOIN + window 통합
2.$facet으로 한 번에 여러 집계 — 대시보드 표준
3.$match를 첫 단계 = 인덱스 활용 + 데이터 축소
공유하기
진행도 43 / 90