第五天
今天学习的是《09 | 实验:聚合查询》章节,主要内容是聚合部分的练习。但其实就讲了一个例子,选梳理了一下语法实现。然后演示了怎么用compass工具来可视化的生成聚合查询。
使用的表
> 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")
},
{
"product" : "Refined Concrete Ball",
"sku" : "1738",
"qty" : 61,
"price" : NumberDecimal("47.00"),
"cost" : NumberDecimal("47")
},
{
"product" : "Rustic Granite Towels",
"sku" : "500",
"qty" : 62,
"price" : NumberDecimal("74.00"),
"cost" : NumberDecimal("62.16")
},
{
"product" : "Refined Rubber Salad",
"sku" : "1400",
"qty" : 73,
"price" : NumberDecimal("93.00"),
"cost" : NumberDecimal("87.42")
},
{
"product" : "Intelligent Wooden Towels",
"sku" : "5674",
"qty" : 72,
"price" : NumberDecimal("84.00"),
"cost" : NumberDecimal("68.88")
},
{
"product" : "Refined Steel Bacon",
"sku" : "5009",
"qty" : 8,
"price" : NumberDecimal("53.00"),
"cost" : NumberDecimal("50.35")
}
],
"total" : NumberDecimal("407")
}
计算所有订单的总销售额
> db.orders.aggregate([{
$group:
{
_id: null,
total: { $sum: "$total"}
}
}])
{ "_id" : null, "total" : NumberDecimal("44019609") }
>
查询2019年第一季度(1月1日~3月31日)已完成订单(completed)的订单总金额和订单总数
>db.orders.aggregate(
[{$match: {
status: "completed",
orderDate: {
$gte: ISODate('2019-01-01'),
$lt: ISODate('2019-04-01')
}
}}, {$group: {
_id: null,
total: {
$sum: "$total"
},
shippingFee: {
$sum: "$shippingFee"
},
count: {
$sum: 1
}
}}, {$project: {
grandTotal: {
$add: ["$total", "$shippingFee"]
},
count: 1,
_id: 0
}}]
)
{ "count" : 5875, "grandTotal" : NumberDecimal("2636376.00") }
使用 Compass
还是用工具比较舒服
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。