반응형
여승철
INTP 개발자
여승철
  • 분류 전체보기 (376)
    • CS (16)
      • 면접 준비 (7)
      • 운영체제 (0)
      • 네트워크 (2)
      • HTTP (6)
      • 스프링(Spring) IoC 컨테이너 (0)
      • 알고리즘 (1)
    • Web (13)
    • AWS (6)
    • Java (43)
    • JSP & Servlet (65)
      • 개념 (42)
      • 실습 (23)
    • Spring Framework (33)
    • Spring Boot (10)
    • Spring Data (22)
      • JPA (14)
      • Query DSL (7)
      • Redis (1)
    • Spring Security (9)
    • Spring Batch (4)
    • MyBatis (10)
    • Front-End (51)
      • JS (27)
      • Vue.js (17)
      • React (5)
      • JQuery (0)
      • d3.js (2)
    • DBMS (24)
      • SQL, RDBMS (16)
      • MongoDB (5)
      • Redis (3)
    • Kafka (3)
    • 리눅스 (Linux) (4)
    • 디자인 패턴 (3)
    • VCS (8)
    • API (0)
    • TOOL (3)
    • Reading Book (28)
      • 이펙티브 자바 (11)
      • Clean Code (10)
      • 1분 설명력 (4)
      • HOW TO 맥킨지 문제해결의 기술 (3)
    • C# (4)
    • NSIS (6)
    • ETC (11)

블로그 메뉴

  • 홈
  • 태그

인기 글

태그

  • 맥킨지
  • ubuntu
  • querydsl
  • servlet
  • mybatis
  • 로그인
  • jsp
  • JDBC
  • Spring Batch
  • 디자인 패턴
  • HTTP
  • 게시판
  • Dao
  • 회원 관리
  • EC2
  • controller
  • 환경 세팅
  • JSTL
  • 이펙티브 자바
  • 스트림

최근 댓글

최근 글

hELLO· Designed By 정상우.
여승철

INTP 개발자

MongoDB  GROUP BY와 유사한 Aggregation
DBMS/MongoDB

MongoDB GROUP BY와 유사한 Aggregation

2024. 1. 31. 10:51
반응형

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
    여승철
    여승철

    티스토리툴바