当前位置: 代码网 > it编程>数据库>Nosql > MongoDB数据库聚合之分组统计$group的用法详解

MongoDB数据库聚合之分组统计$group的用法详解

2024年07月02日 Nosql 我要评论
前言mongodb不像关系型数据库,普通的查询不支持汇总,要进行复杂的分组汇总,需要使用聚合管道,$group可以说是mongodb聚合管道进行数据分析最常用的一个阶段。该阶段根据分组键值(组键)把文

前言

mongodb不像关系型数据库,普通的查询不支持汇总,要进行复杂的分组汇总,需要使用聚合管道,$group可以说是mongodb聚合管道进行数据分析最常用的一个阶段。该阶段根据分组键值(组键)把文档分成若干组,每个唯一的键值对应一个文档。组键通常是一个或多个字段,也可以是表达式的结果。$group阶段输出的结果中,_id字段的值就是组键的值,输出文档中还可以包含汇总表达式的字段,汇总表达式的功能非常丰富,下面的列表会简单介绍,具体的使用方法可以参考详细说明。

$group的语法

{
 $group:
   {
     _id: <expression>, // 组键,就是分组的键值字段或表达式
     <field1>: { <accumulator1> : <expression1> },
     ...
   }
 }

字段说明:

字段说明
_id不可省略,通过_id表达式指定分组的依据,如果直接指定_id的值为null或常量,则把全部的输入文档汇总后返回一个文档
field可选,汇总表达式计算的结果
_id和field可以是任何合法的表达式。

分组汇总操作符

分组汇总操作符比较多,功能丰富且强大,这里简要介绍其用途,详细的用法后续再专文介绍。

操作符用途介绍
$accumulator返回累加结果
$addtoset把分组中不重复的表达式的值作为数组返回,注意数组的元素无序的,类似分组内的distinct
$avg返回数值的平均值。非数值会被忽略
$bottom按照指定的顺序返回分组中最后一个元素
$bottomn按照指定的顺序返回分组中最后n个元素字段的集合,如果分组元素数量小于n,则返回全部
$count返回分组内的元素数量
$first返回分组内第一个元素表达式的结果
$firstn返回分组内前n个元素的聚合。只有文档有序时才有意义
$last返回分组中最后一个文档的表达式的结果
$lastn返回分组内最后n个元素的聚合。只有文档有序时才有意义
$max返回每个分组表达式值的最大值
$maxn返回分组内最大的n个元素的集合
$median返回分组中的中位数
$mergeobjects返回分组合并后的文档
$min返回分组内表达式的最小值
$percentile返回与指定百分位数值相对应的值的数组
$push返回每个分组表达式值的数组
$stddevpop返回标准差
$stddevsamp返回样本标准差
$sum返回合计值,忽略空值
$top根据指定的顺序返回组内最前面的元素
$topn根据指定的顺序返回组内前n个元素的聚合

注意

  • $group使用内存不能超过100m,超过会报错。如果想要处理更多数据或者少用一些内存,可使用allowdiskuse选项把数据写入临时文件。
  • 当使用$first、$last等操作符时,可以考虑在参与排序的分组字段上添加索引,某些情况下,这些操作可以使用索引快速定位到相应的记录。

一些例子

统计数量

创建并插入数据:

db.sales.insertmany([
  { "_id" : 1, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("2"), "date" : isodate("2014-03-01t08:00:00z") },
  { "_id" : 2, "item" : "jkl", "price" : decimal128("20"), "quantity" : int32("1"), "date" : isodate("2014-03-01t09:00:00z") },
  { "_id" : 3, "item" : "xyz", "price" : decimal128("5"), "quantity" : int32( "10"), "date" : isodate("2014-03-15t09:00:00z") },
  { "_id" : 4, "item" : "xyz", "price" : decimal128("5"), "quantity" :  int32("20") , "date" : isodate("2014-04-04t11:21:39.736z") },
  { "_id" : 5, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("10") , "date" : isodate("2014-04-04t21:23:13.331z") },
  { "_id" : 6, "item" : "def", "price" : decimal128("7.5"), "quantity": int32("5" ) , "date" : isodate("2015-06-04t05:08:13z") },
  { "_id" : 7, "item" : "def", "price" : decimal128("7.5"), "quantity": int32("10") , "date" : isodate("2015-09-10t08:43:00z") },
  { "_id" : 8, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("5" ) , "date" : isodate("2016-02-06t20:20:13z") },
])

统计sales全部文档数量

相当于collection.find({}).count()

db.sales.aggregate( [
  {
    $group: {
       _id: null,
       count: { $count: { } }
    }
  }
] )

结果:

{ "_id" : null, "count" : 8 }

检索不同的值,等价于distinct

仍以上例的sales集合数据为例

db.sales.aggregate( [ { $group : { _id : "$item" } } ] )

结果:

{ "_id" : "abc" }
{ "_id" : "jkl" }
{ "_id" : "def" }
{ "_id" : "xyz" }

等价于:

db.sales.distinct("item")

按item分组

下面的聚合先按照item进行分组,计算每个item销售总额,并且返回大于等于100的item。

db.sales.aggregate(
  [
    //阶段1
    {
      $group :
        {
          _id : "$item",
          totalsaleamount: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }
     },
     //阶段2
     {
       $match: { "totalsaleamount": { $gte: 100 } }
     }
   ]
 )

阶段1:$group阶段,根据item进行分组,并计算每个item的销售总额。

阶段2:$math阶段,过滤结果文档,只返回销售总额totalsaleamount大于等于100的文档。

结果:

{ "_id" : "abc", "totalsaleamount" : decimal128("170") }
{ "_id" : "xyz", "totalsaleamount" : decimal128("150") }
{ "_id" : "def", "totalsaleamount" : decimal128("112.5") }

计算总数、合计和平均值

创建一个sales集合并插入记录:

db.sales.insertmany([
  { "_id" : 1, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("2"), "date" : isodate("2014-03-01t08:00:00z") },
  { "_id" : 2, "item" : "jkl", "price" : decimal128("20"), "quantity" : int32("1"), "date" : isodate("2014-03-01t09:00:00z") },
  { "_id" : 3, "item" : "xyz", "price" : decimal128("5"), "quantity" : int32( "10"), "date" : isodate("2014-03-15t09:00:00z") },
  { "_id" : 4, "item" : "xyz", "price" : decimal128("5"), "quantity" :  int32("20") , "date" : isodate("2014-04-04t11:21:39.736z") },
  { "_id" : 5, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("10") , "date" : isodate("2014-04-04t21:23:13.331z") },
  { "_id" : 6, "item" : "def", "price" : decimal128("7.5"), "quantity": int32("5" ) , "date" : isodate("2015-06-04t05:08:13z") },
  { "_id" : 7, "item" : "def", "price" : decimal128("7.5"), "quantity": int32("10") , "date" : isodate("2015-09-10t08:43:00z") },
  { "_id" : 8, "item" : "abc", "price" : decimal128("10"), "quantity" : int32("5" ) , "date" : isodate("2016-02-06t20:20:13z") },
])

按照日期分组

下面的聚合管道计算2014年的销售总额、平均销量和销售数量

db.sales.aggregate([
  //阶段1
  {
    $match : { "date": { $gte: new isodate("2014-01-01"), $lt: new isodate("2015-01-01") } }
  },
  //阶段2
  {
    $group : {
       _id : { $datetostring: { format: "%y-%m-%d", date: "$date" } },
       totalsaleamount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
       averagequantity: { $avg: "$quantity" },
       count: { $sum: 1 }
    }
  },
  //阶段3
  {
    $sort : { totalsaleamount: -1 }
  }
 ])

阶段1使用$math只允许2014年的数据进入下一阶段.

阶段2使用$group根据日期进行分组,统计每个分组的销售总额、平均销量和销售数量。

阶段3使用$sort按照销售总额进行降序排序

结果:

{
   "_id" : "2014-04-04",
   "totalsaleamount" : decimal128("200"),
   "averagequantity" : 15, "count" : 2
}
{
   "_id" : "2014-03-15",
   "totalsaleamount" : decimal128("50"),
   "averagequantity" : 10, "count" : 1
}
{
   "_id" : "2014-03-01",
   "totalsaleamount" : decimal128("40"),
   "averagequantity" : 1.5, "count" : 2
}

按控制null分组

下面的聚合操作,指定分组_id为空,计算集合中所有文档的总销售额、平均数量和计数。

db.sales.aggregate([
  {
    $group : {
       _id : null,
       totalsaleamount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
       averagequantity: { $avg: "$quantity" },
       count: { $sum: 1 }
    }
  }
 ])

结果:

{
  "_id" : null,
  "totalsaleamount" : decimal128("452.5"),
  "averagequantity" : 7.875,
  "count" : 8
}

数据透视

创建books集合并插入数据

db.books.insertmany([
  { "_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 }
])

根据作者对标题分组

下面的聚合操作将books集合中的数据透视为按作者分组的标题。

db.books.aggregate([
   { $group : { _id : "$author", books: { $push: "$title" } } }
 ])

结果

{ "_id" : "homer", "books" : [ "the odyssey", "iliad" ] }
{ "_id" : "dante", "books" : [ "the banquet", "divine comedy", "eclogues" ] }

根据作者对文档分组

db.books.aggregate([
   // 阶段1
   {
     $group : { _id : "$author", books: { $push: "$$root" } }
   },
   // 阶段2
   {
     $addfields:
       {
         totalcopies : { $sum: "$books.copies" }
       }
   }
 ])

阶段1:分组$group,根据作者对文档进行分组,使用$$root把文档作为books的元素。

阶段2:$addfields会在输出文档中添加一个字段,即每位作者的图书总印数。

结果:

{
  "_id" : "homer",
  "books" :
     [
       { "_id" : 7000, "title" : "the odyssey", "author" : "homer", "copies" : 10 },
       { "_id" : 7020, "title" : "iliad", "author" : "homer", "copies" : 10 }
     ],
   "totalcopies" : 20
}

{
  "_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 }
     ],
   "totalcopies" : 5
}

以上内容参考mongodb官方文档整理而来

总结

到此这篇关于mongodb数据库聚合之分组统计$group的用法详解的文章就介绍到这了,更多相关mongodb分组统计$group用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com