반응형
집계 파이프라인 기본
$match는 SQL의 'WHERE', $group은 SQL의 'GROUP BY' 역할.

db.orders.aggregate([
{ $match: { status: "completed" } }, // 필터링
{ $group: { // 그룹화
_id: "$customerId",
totalAmount: { $sum: "$amount" },
orderCount: { $sum: 1 }
}},
{ $sort: { totalAmount: -1 } }, // 정렬
{ $limit: 10 } // 제한
])
주요 집계 단계
($sort와 $limit은 이전 포스팅에서, $match(필터링)와 $group(그룹화)은 위에서 설명했으므로, 나머지 설명.)
$project - 필드 변환
db.users.aggregate([
{ $project: { // 아래 작업들을 적용하겠다 선언
name: 1,
email: 1,
fullName: { $concat: ["$firstName", " ", "$lastName"] },
age: { $subtract: [2024, "$birthYear"] },
isAdult: { $gte: ["$age", 18] }
}}
])
$unwind - 배열 펼치기
db.orders.aggregate([
{ $unwind: "$items" }, // items 배열 펼치기
{ $group: {
_id: "$items.productId",
totalQuantity: { $sum: "$items.quantity" }
}}
])
$lookup - 조인
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer"
}},
{ $unwind: "$customer" }
])
복잡한 집계 예제
// 월별 매출 통계
db.sales.aggregate([
{ $match: {
date: { $gte: new Date("2024-01-01") } // date로 필터링
}},
{ $group: {
_id: {
year: { $year: "$date" },
month: { $month: "$date" } // _id를 year, month로 그룹화하고
},
totalSales: { $sum: "$amount" }, // 각각 총합, 횟수, 평균으로 새로 속성을 만듦
orderCount: { $sum: 1 },
avgOrderValue: { $avg: "$amount" }
}},
{ $sort: { "_id.year": 1, "_id.month": 1 } }, // year, month로 오름차순 정렬
{ $project: { // 필드 변환, 아래 파이프라인 적용
_id: 0, // 기존 _id 필드를 결과에서 숨김 (제거)
period: { $concat: [ // 문자열 결합
{ $toString: "$_id.year" }, // 숫자를 문자열로 변환
"-",
{ $toString: "$_id.month" } // 숫자를 문자열로 변환
]},
totalSales: 1, // 그대로 가져오기
orderCount: 1, // 그대로 가져오기
avgOrderValue: { $round: ["$avgOrderValue", 2] } // 소수점 2번쨰 자리로 반올림
}}
])
반응형
'Database > MongoDB' 카테고리의 다른 글
| MongoDB #6 (VSCode로 MongoDB 사용하기) (1) | 2025.07.28 |
|---|---|
| MongoDB #4 (인덱싱) (0) | 2025.07.28 |
| MongoDB #3 (쿼리 및 필터링) (4) | 2025.07.28 |
| MongoDB #2 (기본 명령어, CRUD) (1) | 2025.07.28 |
| MongoDB #1 (소개) (1) | 2025.07.28 |