MongoDB 聚合操作之 $group 使用

说明:本篇文章主要介绍 $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 操作可以很方便的处理数据,但是需要注意的是,所以的分组数据是无序的,并且都是在内存中操作完成,所有操作的时候,不能支持大数据量。

  • 29
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
MongoDB提供了三种方式来执行聚合操作聚合管道方法、map-reduce方法和单一目标聚合方法。聚合管道方法可以理解为合计流水线法,通过对集合中的文档记录进行分类统计。该方法支持分片集合操作使用聚合管道方法可以通过传递一系列的操作符来实现各种统计操作,比如求和($sum)、求平均值($avg)、取最小值($min)、取最大值($max)等等。聚合管道方法的语法如下: ``` db.collection_name.aggregate( [ {$match:{<field>}}, // 统计查找条件 {$group:{<field1>, <field2>}} // field1为分类字段;field2为含各种统计操作符的数值型字段,如$sum、$avg、$min、$max、$push、$addToSet、$first、$last操作符 ) ``` 聚合分类统计是聚合操作的一种,目前在MongoDB中有两种聚合操作功能:count()和distinct()。count()用于计算满足指定条件的文档数量,distinct()用于返回指定字段的唯一值列表。使用这两个方法可以对集合中的数据进行简单的聚合统计。 我希望这些信息对您有所帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [MongoDB——聚合操作详解](https://blog.csdn.net/cold___play/article/details/121447382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值