MongoDB 数据汇总

MongoDBMongoDBBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何在 MongoDB 中执行基本的聚合操作,包括计算总和、查找最小值和最大值、统计文档数量、计算平均值以及生成报告。实验通过使用一个示例书籍集合来演示 MongoDB 聚合框架的强大功能,帮助你从数据中提取有意义的见解。

实验将逐步引导你完成操作,首先从计算总值开始,例如书籍的总价值和总数量。接着,你将学习如何查找书籍的最低和最高价格、统计文档数量以及计算书籍的平均价格。最后,你将探索如何生成报告以汇总集合中的数据。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("MongoDB")) -.-> mongodb/QueryOperationsGroup(["Query Operations"]) mongodb(("MongoDB")) -.-> mongodb/DataTypesGroup(["Data Types"]) mongodb(("MongoDB")) -.-> mongodb/AggregationOperationsGroup(["Aggregation Operations"]) mongodb/QueryOperationsGroup -.-> mongodb/find_documents("Find Documents") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("Query with Conditions") mongodb/QueryOperationsGroup -.-> mongodb/sort_documents("Sort Documents") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("Project Fields") mongodb/DataTypesGroup -.-> mongodb/use_numeric_data_types("Use Numeric Data Types") mongodb/AggregationOperationsGroup -.-> mongodb/group_documents("Group Documents") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("Aggregate Group Totals") subgraph Lab Skills mongodb/find_documents -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/query_with_conditions -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/sort_documents -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/project_fields -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/use_numeric_data_types -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/group_documents -.-> lab-422093{{"MongoDB 数据汇总"}} mongodb/aggregate_group_totals -.-> lab-422093{{"MongoDB 数据汇总"}} end

计算总和

在这一步骤中,你将学习如何使用 MongoDB 的聚合框架计算总值。我们将使用一个示例书籍集合来演示如何对数值字段进行求和。

首先,启动 MongoDB shell 并创建一个示例书籍集合:

mongosh

接下来,创建一个包含价格的书籍集合:

use bookstore

db.books.insertMany([
    { title: "Python Basics", price: 29.99, quantity: 50 },
    { title: "MongoDB Essentials", price: 39.99, quantity: 30 },
    { title: "Data Science Guide", price: 45.50, quantity: 25 },
    { title: "Web Development", price: 34.75, quantity: 40 }
])

要计算所有书籍的总价值,我们可以使用 $sum 聚合操作符:

db.books.aggregate([
  {
    $group: {
      _id: null,
      totalBookValue: { $sum: { $multiply: ["$price", "$quantity"] } }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    totalBookValue: 5197.25
  }
]

让我们分解一下这个聚合操作的作用:

  • $group 将所有文档分组
  • _id: null 表示我们对整个集合进行聚合
  • $multiply 计算每本书的总价值(价格 * 数量)
  • $sum 将这些值相加

你还可以计算其他总和,例如书籍的总数量:

db.books.aggregate([
  {
    $group: {
      _id: null,
      totalQuantity: { $sum: "$quantity" }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    totalQuantity: 145
  }
]

查找最小值和最大值

在这一步骤中,你将学习如何使用 MongoDB 的聚合框架查找最小值和最大值。我们将继续使用上一步中的书店集合。

首先,验证我们现有的集合:

use bookstore
db.books.find()

要查找书籍的最低和最高价格,我们可以使用 $min$max 聚合操作符:

db.books.aggregate([
  {
    $group: {
      _id: null,
      lowestPrice: { $min: "$price" },
      highestPrice: { $max: "$price" }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    lowestPrice: 29.99,
    highestPrice: 45.50
  }
]

我们还可以查找最小和最大数量:

db.books.aggregate([
  {
    $group: {
      _id: null,
      lowestQuantity: { $min: "$quantity" },
      highestQuantity: { $max: "$quantity" }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    lowestQuantity: 25,
    highestQuantity: 50
  }
]

为了获得更详细的见解,我们可以查找价格最低和最高的书籍:

db.books.aggregate([
  {
    $sort: { price: 1 }
  },
  {
    $limit: 1
  },
  {
    $project: {
      title: 1,
      price: 1
    }
  }
]);

示例输出:

[
  {
    _id: ObjectId("..."),
    title: "Python Basics",
    price: 29.99
  }
]

统计文档数量

在这一步骤中,你将学习使用多种技术在 MongoDB 中统计文档数量的不同方法。我们将继续使用之前步骤中的书店集合。

首先,验证我们现有的集合:

use bookstore
db.books.find()

在 MongoDB 中,有多种方法可以统计文档数量。让我们逐一探索:

  1. 基本统计方法:
db.books.countDocuments();

示例输出:

4
  1. 使用过滤器统计文档数量:
db.books.countDocuments({ price: { $gt: 35 } });

这将统计价格大于 35 的书籍数量。

示例输出:

2
  1. 使用聚合框架进行统计:
db.books.aggregate([
  {
    $match: { quantity: { $gte: 30 } }
  },
  {
    $count: "booksWithHighQuantity"
  }
]);

这将统计数量大于或等于 30 的书籍数量。

示例输出:

[
  {
    booksWithHighQuantity: 3
  }
]
  1. 统计唯一值数量:
db.books.aggregate([
  {
    $group: {
      _id: "$title",
      count: { $sum: 1 }
    }
  }
]);

这将显示每本书的标题出现的次数。

示例输出:

[
  {
    _id: "Python Basics",
    count: 1
  },
  ...
]

计算平均值

在这一步骤中,你将学习如何使用 MongoDB 的聚合框架计算平均值。我们将继续使用之前步骤中的书店集合。

首先,验证我们现有的集合:

use bookstore
db.books.find()
  1. 计算书籍的平均价格:
db.books.aggregate([
  {
    $group: {
      _id: null,
      averagePrice: { $avg: "$price" }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    averagePrice: 37.56
  }
]
  1. 计算平均数量并四舍五入:
db.books.aggregate([
  {
    $group: {
      _id: null,
      averageQuantity: { $avg: "$quantity" }
    }
  },
  {
    $project: {
      averageQuantity: { $round: ["$averageQuantity", 2] }
    }
  }
]);

示例输出:

[
  {
    _id: null,
    averageQuantity: 36.25
  }
]
  1. 按条件分组计算平均价格:
db.books.aggregate([
  {
    $group: {
      _id: {
        priceCategory: {
          $switch: {
            branches: [
              { case: { $lt: ["$price", 35] }, then: "Budget" },
              { case: { $gte: ["$price", 35] }, then: "Premium" }
            ]
          }
        }
      },
      averagePrice: { $avg: "$price" }
    }
  }
]);

示例输出:

[
  {
    _id: { priceCategory: "Budget" },
    averagePrice: 32.37
  },
  {
    _id: { priceCategory: "Premium" },
    averagePrice: 42.75
  }
]

生成报告

在这最后一步中,你将学习如何使用 MongoDB 的聚合框架生成更复杂的报告。我们将结合多个聚合阶段,从书店集合中创建有洞察力的报告。

首先,验证我们现有的集合:

use bookstore
db.books.find()
  1. 综合书籍库存报告:
db.books.aggregate([
  {
    $project: {
      title: 1,
      totalValue: { $multiply: ["$price", "$quantity"] },
      inventoryStatus: {
        $switch: {
          branches: [
            { case: { $lt: ["$quantity", 30] }, then: "Low Stock" },
            { case: { $gte: ["$quantity", 30] }, then: "In Stock" }
          ]
        }
      }
    }
  },
  {
    $sort: { totalValue: -1 }
  }
]);

示例输出:

[
  {
    _id: ObjectId("..."),
    title: "Python Basics",
    totalValue: 1499.50,
    inventoryStatus: "In Stock"
  },
  ...
]
  1. 价格范围分布报告:
db.books.aggregate([
  {
    $bucket: {
      groupBy: "$price",
      boundaries: [0, 35, 45, 100],
      default: "Other",
      output: {
        count: { $sum: 1 },
        titles: { $push: "$title" }
      }
    }
  }
]);

示例输出:

[
  {
    _id: 0,
    count: 2,
    titles: ["Python Basics", "Web Development"]
  },
  {
    _id: 35,
    count: 1,
    titles: ["MongoDB Essentials"]
  },
  ...
]
  1. 详细销售绩效报告:
db.books.aggregate([
  {
    $group: {
      _id: {
        priceCategory: {
          $switch: {
            branches: [
              { case: { $lt: ["$price", 35] }, then: "Budget" },
              { case: { $gte: ["$price", 35] }, then: "Premium" }
            ]
          }
        }
      },
      totalBooks: { $sum: 1 },
      totalQuantity: { $sum: "$quantity" },
      totalValue: { $sum: { $multiply: ["$price", "$quantity"] } },
      avgPrice: { $avg: "$price" }
    }
  },
  {
    $project: {
      _id: 0,
      priceCategory: "$_id.priceCategory",
      totalBooks: 1,
      totalQuantity: 1,
      totalValue: { $round: ["$totalValue", 2] },
      avgPrice: { $round: ["$avgPrice", 2] }
    }
  }
]);

示例输出:

[
  {
    priceCategory: "Budget",
    totalBooks: 2,
    totalQuantity: 90,
    totalValue: 2984.50,
    avgPrice: 32.37
  },
  {
    priceCategory: "Premium",
    totalBooks: 2,
    totalQuantity: 55,
    totalValue: 2212.75,
    avgPrice: 42.75
  }
]

总结

在本实验中,你将学习如何使用 MongoDB 的聚合框架计算总和、查找最小值和最大值、统计文档数量、计算平均值以及生成报告。首先,你将使用 $sum 聚合操作符计算示例书籍集合中所有书籍的总价值。你还将学习如何计算书籍的总数量。接下来,你将使用 $min$max 聚合操作符查找书籍的最低和最高价格。然后,你将学习如何统计集合中的文档数量并计算书籍的平均价格。