MongoDB 聚合框架 (2/2)

演示数据模型,一条订单,如下

  //> db.orders.findOne()
  {
  	"_id" : ObjectId("5dbe7a545368f69de2b4d36e"),

  	"street" : "493 Hilll Curve",
  	"city" : "Champlinberg",
  	"state" : "Texas",
  	"country" : "Malaysia",
  	"zip" : "24344-1715",
  	"phone" : "425.956.7743 x4621",
  	"name" : "Destinee Schneider",
  	"userId" : 3573,
  	"orderDate" : ISODate("2019-03-26T03:20:08.805Z"),
  	"status" : "created",
  	"shippingFee" : NumberDecimal("8.00"),
  	"orderLines" : [
  		{
  			"product" : "Refined Fresh Tuna",
  			"sku" : "2057",
  			"qty" : 25,
  			"price" : NumberDecimal("56.00"),
  			"cost" : NumberDecimal("46.48")
  		},
  		{/*商品2*/},
  		{/*商品3*/},
  		{/*商品4*/}
  	],
  	"total" : NumberDecimal("158.99")
  }

实验一、计算到目前为止的所有订单的总销售额。

db.orders.aggregate([
	{$group : 
		{
			_id : null, // 按照哪个字段分组,这里不涉及到分组,"_id:null"相当于表示没有分组。
			total : { $sum : "$total"} // 把订单的 total 字段 sum 起来。
		}
	}
])
// 结果: // {"_id" : null, "total" : NumberDecimal("441709.63")}

实验二、查询2019年第一季度(1/1~3/31)已完成(status=completed)的订单总金额和订单总数。

db.orders.aggregate([
	// 步骤1: 匹配时间和订单状态,先匹配减少运算的数据量。
	{$match : { status : "completed", orderDate : {
		$gte : ISODate("2009-01-01"),
		$lt : ISODate("2019-04-01")}}},
	// 步骤2: 聚合订单总金额、总运费、总数量
	{$group : {
		_id: null, // 不分组
		total: {$sum: "$total"}, // 订单总金额
		shippingFee: {$sum: "$shippingFee"}, // 运费总金额
		count: {$sum: 1}}},
	{$project : {
		// 计算总金额
		grandTotal: {$add: ["$total", "$shippingFee"]},
		count: 1, // 1 表示把上一步骤计算出的count字段包括进来进行返回。
		_id: 0 }} // 0 不返回id字段。
])
// 结果: // {"count": 5875, "grandTotal": NumberDecimal("2636376.42")}

实验三、可视 - 聚合构建器(略)

  1. 使用 MongoDB Compass 软件构建调试。
  2. 选中一个表,选择 Aggregtaions。
  3. 添加 Pipeline、Stage 进行聚合框架的构建调试。
  4. Export Pipeline To。导出到几种编程语言(Java等)。
原文地址:https://www.cnblogs.com/sweetXiaoma/p/14582725.html