聚合

适用对象: MongoDB vCore

aggregate 命令用于处理数据记录并返回计算结果。 它对数据执行操作,例如筛选、分组和排序,并且可以以各种方式转换数据。 aggregate 命令用途广泛,常用于数据分析和报告。

语法

db.collection.aggregate(pipeline, options)
  • 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 }
]
 

示例 2:查找全职员工人数大于 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' ]
  }
]

示例 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" }
    }
  }
])

示例输出

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