聚合例子

数据集

假设有一个名为 books 的图书集合,其示例数据结构如下:

  1. {
  2. "_id": "xxxx-xxxx-xxxx",
  3. "category": "novel",
  4. "title": "title 1",
  5. "author": "author 1",
  6. "sales": 5000,
  7. "monthlySales": [1000, 1500, 2500]
  8. }

例:求各类图书的平均销量

采用 books 图书数据集作为示例。求各类图书的平均销量的操作等价于将图书按类别(category)分组,然后对每组的销量(sales)求平均值,最后返回类别和平均销量信息。

  1. const db = wx.cloud.database()
  2. const $ = db.command.aggregate
  3. const result = await db.collection('books').aggregate()
  4. .group({
  5. // 按 category 字段分组
  6. _id: '$category',
  7. // 每组有一个 avgSales 字段,其值是组内所有记录的 sales 字段的平均值
  8. avgSales: $.avg('$sales')
  9. })
  10. .end()

返回结果示例如下:

  1. {
  2. "list": [
  3. {
  4. _id: "novel", // 组名
  5. sales: 1035, // 组平均销量
  6. },
  7. {
  8. _id: "science", // 组名
  9. sales: 350, // 组平均销量
  10. }
  11. ]
  12. }

用到的聚合流水线阶段:group

用到的聚合流水线操作符:avg

例:求各类图书的最高销量作者和最低销量作者及其销量

采用 books 图书数据集作为示例。一个作者在一个图书类目下可能有多本书,这个操作可以分阶段进行批处理:

  • 第一阶段: 按 “图书类目 + 作者” 进行分组,求得每个作者在该图书类目下的多本书的总销量
  • 第二阶段: 将上一个阶段得到的结果按总销量排倒序,求得各图书类目作者的总销量排序
  • 第三阶段: 将上一个阶段得到的结果按类目分组,各组分别取组中第一项(销量最高)和最后一项(销量最低)的作者名和总销量,返回最终结果
  1. const db = wx.cloud.database()
  2. const $ = db.command.aggregate
  3. const result = db.collection('books').aggregate()
  4. .group({
  5. _id: {
  6. category: '$category',
  7. author: '$author',
  8. },
  9. totalSales: $.sum('$sales')
  10. })
  11. .sort({
  12. totalSales: -1,
  13. })
  14. .group({
  15. _id: '$_id.category',
  16. bestSellingAuthor: $.first('$_id.author'),
  17. bestSellingAuthorTotalSales: $.first('$totalSales'),
  18. worstSellingAuthor: $.last('$_id.author'),
  19. worstSellingAuthorTotalSales: $.last('$totalSales'),
  20. })
  21. .end().then(console.log)

返回结果示例如下:

  1. {
  2. "list": [
  3. {
  4. "_id": "novel",
  5. "bestSellingAuthor": "author 1",
  6. "bestSellingAuthorTotalSales": 550,
  7. "worstSellingAuthor": "author 2",
  8. "worstSellingAuthorTotalSales": 1520
  9. },
  10. {
  11. "_id": "science",
  12. "bestSellingAuthor": "author 4",
  13. "bestSellingAuthorTotalSales": 1050,
  14. "worstSellingAuthor": "author 3",
  15. "worstSellingAuthorTotalSales": 3000
  16. }
  17. ]
  18. }

用到的聚合流水线阶段:groupsort

用到的聚合流水线操作符:sumfirstlast