共用方式為


彙總

aggregate 指令用於處理資料記錄並回傳計算結果。 它對資料執行過濾、分組與排序等操作,並能以多種方式轉換資料。 此 aggregate 指令高度靈活,常用於資料分析與報告。

語法

db.collection.aggregate(pipeline, options)
  • 管線:一系列聚合階段,用以處理與轉換資料。
  • 選項:可選。 指定更多聚合選項,如 explainallowDiskUsecursor

範例

範例 1:按類別計算總銷售額

此範例示範如何計算集合中 stores 每個類別的總銷售額。

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

範例輸出

[mongos] StoreData> 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 }
]
 

範例二:尋找全職員工超過10人的門市

此範例展示了如何篩選全職員工超過10人的門市。

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

範例輸出

[mongos] StoreData> 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' ]
  }
]

範例三:列出所有折扣超過15% 的促銷活動

此範例列出所有促銷活動中任何折扣超過15%。

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

範例輸出

[mongos] StoreData> db.stores.aggregate([
...   {
...     $unwind: "$promotionEvents"
...   },
...   {
...     $unwind: "$promotionEvents.discounts"
...   },
...   {
...     $match: {
...       "promotionEvents.discounts.discountPercentage": { $gt: 20 }
...     }
...   },
...   {
...     $group: {
...       _id: "$promotionEvents.eventName",
...       discounts: { $push: "$promotionEvents.discounts" }
...     }
...   }
... ])
[
  {
    [
      { categoryName: 'Basketball Gear', discountPercentage: 23 },
      { categoryName: 'Wool Carpets', discountPercentage: 22 },
      {
        categoryName: 'Portable Bluetooth Speakers',
        discountPercentage: 24
      }
    ]
  }
]