MongoDB 聚合操作之 $group 使用-分组

MongoDB 聚合操作之 $group 使用

Wayfreem

说明:本篇文章主要介绍 $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 的平均数

 
  1. db.sales.aggregate([

  2. {

  3. $group : {

  4. _id : "$item",

  5. totalPrice: { $sum : "$price"},

  6. avgQuantity: { $avg: "$quantity" }

  7. }

  8. }

  9. ]);

  10.  
  11. // 返回结果

  12. { "_id" : "xyz", "totalPrice" : 10, "avgQuantity" : 15 }

  13. { "_id" : "jkl", "totalPrice" : 20, "avgQuantity" : 1 }

  14. { "_id" : "abc", "totalPrice" : 20, "avgQuantity" : 6 }

 

示例:按照 item 字段进行分组,统计每个 item 下面 quantity 的最大值与最小值

 
  1. db.sales.aggregate([

  2. {

  3. $group : {

  4. _id : "$item",

  5. maxQuantity: { $max : "$quantity"},

  6. minQuantity: { $min: "$quantity" }

  7. }

  8. }

  9. ]);

  10.  
  11. // 返回结果

  12. { "_id" : "xyz", "maxQuantity" : 20, "minQuantity" : 10 }

  13. { "_id" : "jkl", "maxQuantity" : 1, "minQuantity" : 1 }

  14. { "_id" : "abc", "maxQuantity" : 10, "minQuantity" : 2 }

 

示例:保留第一个内容与保留最后一个内容

 
  1. db.sales.aggregate([

  2. {

  3. $group : {

  4. _id : "$item",

  5. first: { $first : "$quantity"},

  6. }

  7. }

  8. ]);

  9.  
  10. // 返回结果

  11. { "_id" : "xyz", "first" : 10 }

  12. { "_id" : "jkl", "first" : 1 }

  13. { "_id" : "abc", "first" : 2 }

 

 
  1. db.sales.aggregate([

  2. {

  3. $group : {

  4. _id : "$item",

  5. last: { $last : "$quantity"},

  6. }

  7. }

  8. ]);

  9.  
  10. // 返回结果

  11. { "_id" : "xyz", "last" : 20 }

  12. { "_id" : "jkl", "last" : 1 }

  13. { "_id" : "abc", "last" : 10 }

 

示例:按月,日和年对文档进行分组,并计算总价格和平均数量,并计算每个组的文档个数

 
  1. ​​​​​​db.sales.aggregate([

  2. {

  3. $group : {

  4. // _id : { filed : value } 这个结构是自定义,用来定义按照什么分组

  5. // "$date" 表示操作这个字段, $month、$dayOfMonth 和 $year 是表示从 $date 里面取出对应日期数据

  6. _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },

  7.  
  8. // [ "$price", "$quantity" ] 指的是操作这两个数据,$multiply 对多个字段进行求和操作

  9. totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },

  10.  
  11. // "$quantity" 值的是操作这个数据,$avg 来求平均数

  12. averageQuantity: { $avg: "$quantity" },

  13. // 统计有几条集合数据

  14. count: { $sum: 1 }

  15. }

  16. }

  17. ]);

  18.  
  19. // 返回结果:

  20. { "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "totalPrice" : 200, "averageQuantity" : 15, "count" : 2 }

  21. { "_id" : { "month" : 3, "day" : 15, "year" : 2014 }, "totalPrice" : 50, "averageQuantity" : 10, "count" : 1 }

  22. { "_id" : { "month" : 3, "day" : 1, "year" : 2014 }, "totalPrice" : 40, "averageQuantity" : 1.5, "count" : 2 }

图示:

 

 

特殊的操作方式

除了上面一种操作之后,官方还介绍了另外一操作方式

 
  1. // 数据如下

  2. { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }

  3. { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }

  4. { "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }

  5. { "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }

  6. { "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

示例一: 使用 $push 操作,将数据拼接到一个数组中

 
  1. // 按照 author 分组,将同一个 author 的title 拼接到一个数组中

  2. db.books.aggregate(

  3. [

  4. { $group : { _id : "$author", books: { $push: "$title" } } }

  5. ]

  6. );

  7.  
  8. // 返回结果

  9. { "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }

  10. { "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }

在上面的操作中存在一个问题,如果是存在重复的数据,重复的数据也会一起放入到返回的结果中,对于这样子的情况使用以下操作:

 
  1. // 使用 $addToSet 操作

  2. db.books.aggregate(

  3. [

  4. { $group : { _id : "$author", books: { $addToSet: "$title" } } }

  5. ]

  6. );

示例二: 使用 $$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 操作可以很方便的处理数据,但是需要注意的是,所以的分组数据是无序的,并且都是在内存中操作完成,所有操作的时候,不能支持大数据量。

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值