본문으로 건너뛰기
기술 노트 목록

MongoDB 집계 연산

Database/MongoDB. 2024-12-13에 씀. 3분 분량

Database, MongoDB

MongoDB 집계 연산

aggregate()

설명

집계 파이프라인을 실행하여 데이터를 처리하고 계산된 결과를 반환합니다.

구문

db.collection.aggregate([
    { stage1 },
    { stage2 },
    ...
])

기본 예제

// 사용자의 평균 나이 계산
db.users.aggregate([
    { $group: {
        _id: null,
        averageAge: { $avg: "$age" }
    }}
])

주요 집계 파이프라인 단계

$match

설명

문서를 필터링합니다.

예제

// 나이가 25세 이상인 사용자 필터링
db.users.aggregate([
    { $match: { age: { $gte: 25 }}}
])

$group

설명

지정된 식별자로 문서를 그룹화합니다.

예제

// 국가별 사용자 수 계산
db.users.aggregate([
    { $group: {
        _id: "$country",
        totalUsers: { $sum: 1 }
    }}
])

$sort

설명

문서를 정렬합니다.

예제

// 나이순으로 정렬
db.users.aggregate([
    { $sort: { age: -1 }}
])

$project

설명

출력할 필드를 선택하거나 재정의합니다.

예제

// 이름과 나이만 선택하고 나이에 1을 더함
db.users.aggregate([
    { $project: {
        name: 1,
        adjustedAge: { $add: ["$age", 1] }
    }}
])

$unwind

설명

배열 필드를 해제하여 각 요소당 하나의 문서를 생성합니다.

예제

// 태그별로 문서 분리
db.posts.aggregate([
    { $unwind: "$tags" }
])

$lookup

설명

다른 컬렉션과 조인을 수행합니다.

예제

// 사용자와 주문 정보 조인
db.users.aggregate([
    { $lookup: {
        from: "orders",
        localField: "_id",
        foreignField: "userId",
        as: "userOrders"
    }}
])

집계 연산자

산술 연산자

// $add: 덧셈
{ $add: [<expression1>, <expression2>, ...] }

// $subtract: 뺄셈
{ $subtract: [<expression1>, <expression2>] }

// $multiply: 곱셈
{ $multiply: [<expression1>, <expression2>, ...] }

// $divide: 나눗셈
{ $divide: [<expression1>, <expression2>] }

// 예제
db.sales.aggregate([
    { $project: {
        item: 1,
        total: { $add: ["$price", "$tax"] },
        profit: { $subtract: ["$price", "$cost"] },
        unitPrice: { $divide: ["$total", "$quantity"] }
    }}
])

배열 연산자

// $size: 배열 크기
{ $size: <array expression> }

// $filter: 배열 필터링
{ $filter: {
    input: <array>,
    as: <string>,
    cond: <expression>
}}

// 예제
db.inventory.aggregate([
    { $project: {
        item: 1,
        tagCount: { $size: "$tags" },
        activeTags: {
            $filter: {
                input: "$tags",
                as: "tag",
                cond: { $eq: ["$$tag.status", "active"] }
            }
        }
    }}
])

날짜 연산자

// $year: 연도 추출
{ $year: <date expression> }

// $month: 월 추출
{ $month: <date expression> }

// $dayOfMonth: 일 추출
{ $dayOfMonth: <date expression> }

// 예제
db.sales.aggregate([
    { $project: {
        year: { $year: "$date" },
        month: { $month: "$date" },
        day: { $dayOfMonth: "$date" }
    }}
])

고급 집계 예제

복잡한 그룹화 및 계산

// 월별, 제품별 매출 집계
db.sales.aggregate([
    // 날짜별 필터링
    { $match: {
        date: {
            $gte: new Date("2024-01-01"),
            $lt: new Date("2025-01-01")
        }
    }},
    // 월별, 제품별 그룹화
    { $group: {
        _id: {
            month: { $month: "$date" },
            product: "$productName"
        },
        totalSales: { $sum: "$amount" },
        count: { $sum: 1 }
    }},
    // 결과 정렬
    { $sort: {
        "_id.month": 1,
        "totalSales": -1
    }}
])

다중 컬렉션 조인 및 데이터 변환

// 사용자, 주문, 제품 정보 조합
db.users.aggregate([
    // 사용자와 주문 조인
    { $lookup: {
        from: "orders",
        localField: "_id",
        foreignField: "userId",
        as: "orders"
    }},
    // 주문 배열 해제
    { $unwind: "$orders" },
    // 주문과 제품 조인
    { $lookup: {
        from: "products",
        localField: "orders.productId",
        foreignField: "_id",
        as: "orders.product"
    }},
    // 필요한 필드만 선택
    { $project: {
        name: 1,
        "orders.date": 1,
        "orders.product.name": 1,
        "orders.quantity": 1
    }}
])

다른 기술 노트 보기