aggregate

aggregate 명령은 데이터 레코드를 처리하고 계산된 결과를 반환하는 데 사용됩니다. 필터링, 그룹화 및 정렬과 같은 데이터에 대한 작업을 수행하고 다양한 방법으로 데이터를 변환할 수 있습니다. 이 aggregate 명령은 매우 다양하며 데이터 분석 및 보고에 일반적으로 사용됩니다.

문법

db.collection.aggregate(pipeline, options)
  • 파이프라인: 데이터를 처리하고 변환하는 집계 단계의 배열입니다.
  • 옵션: 선택 사항입니다. 집계에 대한 추가 옵션(예: explain, allowDiskUsecursor.)을 지정합니다.

예시

예제 1: 범주별 총 판매액 계산

이 예제에서는 컬렉션의 각 범주에 대한 총 판매량을 계산하는 stores 방법을 보여 줍니다.

db.stores.aggregate([
  {
    $unwind: "$sales.salesByCategory"
  },
  {
    $group: {
      _id: "$sales.salesByCategory.categoryName",
      totalSales: { $sum: "$sales.salesByCategory.totalSales" }
    }
  }
])

샘플 출력

[
  { "_id": "Christmas Trees", "totalSales": 3147281 },
  { "_id": "Nuts", "totalSales": 3002332 },
  { "_id": "Camping Tables", "totalSales": 4431667 }
]

예제 2: 10명 이상의 정규직 직원이 있는 매장 찾기

이 예제에서는 정규직 직원 수가 10보다 큰 저장소를 필터링하는 방법을 보여줍니다.

db.stores.aggregate([
  {
    $match: {
      "staff.totalStaff.fullTime": { $gt: 10 }
    }
  }
])

샘플 출력

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "name": "Lenore's DJ Equipment Store",
    "location": { "lat": -9.9399, "lon": -0.334 },
    "staff": { "totalStaff": { "fullTime": 18, "partTime": 7 } },
    "sales": {
      "totalSales": 35911,
      "salesByCategory": [ { "categoryName": "DJ Headphones", "totalSales": 35911 } ]
    },
    "promotionEvents": [
      {
        "discounts": [
          { "categoryName": "DJ Turntables", "discountPercentage": 18 },
          { "categoryName": "DJ Mixers", "discountPercentage": 15 }
        ]
      }
    ],
    "tag": [ "#SeasonalSale", "#FreeShipping", "#MembershipDeals" ]
  }
]

예제 3: 할인이 15개보다 큰 모든 프로모션 이벤트 나열%

이 예제에서는 할인이 15개%초과하는 모든 프로모션 이벤트를 나열합니다.

db.stores.aggregate([
  {
    $unwind: "$promotionEvents"
  },
  {
    $unwind: "$promotionEvents.discounts"
  },
  {
    $match: {
      "promotionEvents.discounts.discountPercentage": { $gt: 15 }
    }
  },
  {
    $group: {
      _id: "$promotionEvents.eventName",
      discounts: { $push: "$promotionEvents.discounts" }
    }
  }
])

샘플 출력

[
  {
    "discounts": [
      { "categoryName": "Basketball Gear", "discountPercentage": 23 },
      { "categoryName": "Wool Carpets", "discountPercentage": 22 },
      {
        "categoryName": "Portable Bluetooth Speakers",
        "discountPercentage": 24
      }
    ]
  }
]