说明:本篇文章主要介绍 $group 的各种操作。
MongoDB 聚合操作 $group 使用
基础使用
"$group"
$group 进行分布查询操作。这个有点类似于我们在 SQL 中的 group by 语法,但是这个可以操作的内容多一些。
官方地址:https://docs.mongodb.com/manual/reference/operator/aggregation/group/index.html
语法
{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
参数说明:
- _id :强制必须存在。可以为 null。
其余的计算字段是可选的,并使用 <accumulator> 运算符计算。具体的使用,通过下面的代码说明:
首先准备一点数据:
// 插入数据
db.getCollection('sales').insertMany([
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") },
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") },
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") },
{ "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") },
{ "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") }
]);
插入数据之后,查询刚刚增加的数据
示例:按照 item 字段进行分组,统计每个 item 下面的文档个数
db.sales.aggregate([
{
$group : {
_id : "$item",
count: { $sum : 1}
}
}
]);
// 返回结果
{ "_id" : "xyz", "count" : 2 }
{ "_id" : "jkl", "count" : 1 }
{ "_id" : "abc", "count" : 2 }
示例:按照 item 字段进行分组,统计每个 item 下面 price 的总数,quantity 的平均数
db.sales.aggregate([
{
$group : {
_id : "$item",
totalPrice: { $sum : "$price"},
avgQuantity: { $avg: "$quantity" }
}
}
]);
// 返回结果
{ "_id" : "xyz", "totalPrice" : 10, "avgQuantity" : 15 }
{ "_id" : "jkl", "totalPrice" : 20, "avgQuantity" : 1 }
{ "_id" : "abc", "totalPrice" : 20, "avgQuantity" : 6 }
示例:按照 item 字段进行分组,统计每个 item 下面 quantity 的最大值与最小值
db.sales.aggregate([
{
$group : {
_id : "$item",
maxQuantity: { $max : "$quantity"},
minQuantity: { $min: "$quantity" }
}
}
]);
// 返回结果
{ "_id" : "xyz", "maxQuantity" : 20, "minQuantity" : 10 }
{ "_id" : "jkl", "maxQuantity" : 1, "minQuantity" : 1 }
{ "_id" : "abc", "maxQuantity" : 10, "minQuantity" : 2 }
示例:保留第一个内容与保留最后一个内容
db.sales.aggregate([
{
$group : {
_id : "$item",
first: { $first : "$quantity"},
}
}
]);
// 返回结果
{ "_id" : "xyz", "first" : 10 }
{ "_id" : "jkl", "first" : 1 }
{ "_id" : "abc", "first" : 2 }
db.sales.aggregate([
{
$group : {
_id : "$item",
last: { $last : "$quantity"},
}
}
]);
// 返回结果
{ "_id" : "xyz", "last" : 20 }
{ "_id" : "jkl", "last" : 1 }
{ "_id" : "abc", "last" : 10 }
示例:按月,日和年对文档进行分组,并计算总价格和平均数量,并计算每个组的文档个数
db.sales.aggregate([
{
$group : {
// _id : { filed : value } 这个结构是自定义,用来定义按照什么分组
// "$date" 表示操作这个字段, $month、$dayOfMonth 和 $year 是表示从 $date 里面取出对应日期数据
_id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
// [ "$price", "$quantity" ] 指的是操作这两个数据,$multiply 对多个字段进行乘法操作
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
// "$quantity" 值的是操作这个数据,$avg 来求平均数
averageQuantity: { $avg: "$quantity" },
// 统计有几条集合数据
count: { $sum: 1 }
}
}
]);
// 返回结果:
{ "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "totalPrice" : 200, "averageQuantity" : 15, "count" : 2 }
{ "_id" : { "month" : 3, "day" : 15, "year" : 2014 }, "totalPrice" : 50, "averageQuantity" : 10, "count" : 1 }
{ "_id" : { "month" : 3, "day" : 1, "year" : 2014 }, "totalPrice" : 40, "averageQuantity" : 1.5, "count" : 2 }
图示:
特殊的操作方式
除了上面一种操作之后,官方还介绍了另外一操作方式
// 数据如下
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
示例一: 使用 $push 操作,将数据拼接到一个数组中
// 按照 author 分组,将同一个 author 的title 拼接到一个数组中
db.books.aggregate(
[
{ $group : { _id : "$author", books: { $push: "$title" } } }
]
);
// 返回结果
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }
在上面的操作中存在一个问题,如果是存在重复的数据,重复的数据也会一起放入到返回的结果中,对于这样子的情况使用以下操作:
// 使用 $addToSet 操作
db.books.aggregate(
[
{ $group : { _id : "$author", books: { $addToSet: "$title" } } }
]
);
示例二: 使用 $$ROOT (系统变量)操作
返回生成的文档不得超过BSON文档大小限制。
// 查询操作
db.books.aggregate(
[
{ $group : { _id : "$author", books: { $push: "$$ROOT" } } }
]
)
// 返回结果
{
"_id" : "Homer",
"books" :
[
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
]
}
{
"_id" : "Dante",
"books" :
[
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
]
}
注
虽然使用 $group 操作可以很方便的处理数据,但是需要注意的是,所以的分组数据是无序的,并且都是在内存中操作完成,所有操作的时候,不能支持大数据量。