Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 중첩 $group과 $sum으로 동일한 ProductID별 재고 수량 구하는 방법

MongoDB $group 연산자 개요

MongoDB의 $group 연산자는 지정한 _id 표현식을 기준으로 입력 문서들을 하나의 그룹으로 묶어주는 애그리게이션 단계입니다. 이를 $sum, $addToSet 등의 누적 연산자와 함께 사용하면 제품별 재고 수량이나 합계 금액 같은 통계를 손쉽게 계산할 수 있습니다.

이번 글에서는 중첩 $group과 $sum을 활용하여 유사한 ProductID를 가진 상품의 재고 수를 구하는 방법을 예제와 함께 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 예제로 사용할 컬렉션에 문서를 삽입합니다.

> db.demo466.insertOne(
... {
...    "ProductPrice" :150,
...    "ProductQuantity" : 1,
...    "ProductName" : "Product-1",
...    "ActualAmount" :110,
...    "ProductProfit" : 40,
...    "ProductId" : 1
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e80477cb0f3fa88e2279066") }

> db.demo466.insertOne(
... {
...    "ProductPrice" :150,
...    "ProductQuantity" : 1,
...    "ProductName" : "Product-1",
...    "ActualAmount" :110,
...    "ProductProfit" : 40,
...    "ProductId" : 2
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e80477db0f3fa88e2279067") }

> db.demo466.insertOne(
... {
...    "ProductPrice" :170,
...    "ProductQuantity" : 2,
...    "ProductName" : "Product-2",
...    "ActualAmount" :130,
...    "ProductProfit" : 50,
...    "ProductId" : 3
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e80477eb0f3fa88e2279068") }

2. 저장된 문서 확인하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.

> db.demo466.find();

위 쿼리는 다음과 같은 결과를 출력합니다.

{ "_id" : ObjectId("5e80477cb0f3fa88e2279066"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 1 }
{ "_id" : ObjectId("5e80477db0f3fa88e2279067"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 2 }
{ "_id" : ObjectId("5e80477eb0f3fa88e2279068"), "ProductPrice" : 170, "ProductQuantity" : 2,
"ProductName" : "Product-2", "ActualAmount" : 130, "ProductProfit" : 50, "ProductId" : 3 }

3. 중첩 $group과 $sum을 활용한 집계 쿼리

다음은 MongoDB에서 중첩 $group과 $sum을 사용하여 제품명(ProductName)별로 재고 정보를 집계하는 쿼리입니다.

> db.demo466.aggregate([
... {
...    '$group': {
...       '_id': {
...          'ProductName': '$ProductName',
...       },
...       'ActualAmount': {'$sum': '$ActualAmount'},
...       'ProductQuantity': {'$sum': '$ProductQuantity'},
...       'ProductId': {'$addToSet': '$ProductId'},
...    },
... },
... {
...    '$project': {
...       'ProductQuantity': true,
...       'ActualAmount': true,
...       'NumberOfProductInStock': {'$size': '$ProductId'}
...    }
... }])

쿼리 동작 방식

  • $group: ProductName 필드를 기준으로 문서를 그룹화합니다.
  • $sum: 각 그룹 내의 ActualAmount(실제 금액)와 ProductQuantity(수량)를 합산합니다.
  • $addToSet: 그룹 내 고유한 ProductId 값들을 배열로 모읍니다. 중복 없이 저장되기 때문에 서로 다른 ProductID의 개수를 파악할 수 있습니다.
  • $project$size: ProductId 배열의 크기를 계산하여 NumberOfProductInStock(재고 내 상품 수) 필드로 출력합니다.

실행 결과

위 애그리게이션 쿼리는 다음과 같은 출력을 생성합니다.

{ "_id" : { "ProductName" : "Product-2" }, "ActualAmount" : 130, "ProductQuantity" : 2,
"NumberOfProductInStock" : 1 }
{ "_id" : { "ProductName" : "Product-1" }, "ActualAmount" : 220, "ProductQuantity" : 2,
"NumberOfProductInStock" : 2 }

결과를 보면 Product-1은 두 개의 서로 다른 ProductID(1, 2)를 가지고 있어 재고 내 상품 수가 2로 계산되었고, Product-2는 하나의 ProductID만 있으므로 1로 계산된 것을 확인할 수 있습니다. 이처럼 $group, $sum, $addToSet, $size를 조합하면 복잡한 재고 집계도 간단하게 처리할 수 있습니다.