17

MongoDB聚合(aggregate)

 4 years ago
source link: http://www.cnblogs.com/kungfupanda/p/12630198.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、基础

1、什么是聚合?

聚合是基于数据处理的聚合管道,每个文档通过一个有多个阶段(stage)组成的管道

可以对每个阶段的管道进行分组、过滤等功能,然后经过一系列的处理,输出相应的结果

db.集合名称.aggregate({管道: {表达式}})

有点像Django中ORM聚合的语法

2、常用管道


$group: 将集合中的文档分组,用于统计结果
$match: 过滤数据,只输出符合条件的文档
$project: 修改输入文档的结构,如重命名、增加、删除字段、创建计算结果

$sort: 将输入文档排序后输出
$limit: 限制聚合管道返回的文档数
$skip: 跳过指定数量的文档,并返回余下的文档
$unwind(): 将列表(数组)类型的字段进行拆分

3、常用表达式


处理输入文档,并输出
语法: 表达式:'$列名'
常用表达式
$sum: 计算总和, $sum:1 表示以一倍计数
$avg: 计数平均值
$min: 获取最小值
$max: 获取最大值
$push: 在结果文档中插入值到一个数组中
$first: 根据资源文档的排序获取第一个文档数据
$last: 根据资源文档的排序获取最后一个文档数据

二、常用管道用法

1、$group


作用: 将集合中的文档分组,可用于统计结果
_id表示分组的依据,使用某个字段的格式为'$字段'
格式
db.集合名称.aggregate({$group:{ _id: '$字段', 自定义字段: {表达式: '$字段'}}})

db.stu.aggregate({$group: {_id: '$gender'}})
db.stu.aggregate({$group: {_id: '$gender', count: {$sum: 1}}})
db.stu.aggregate({$group: {_id: '$gender', avg_age: {$avg: '$age'}}})
db.stu.aggregate({$group: {_id: '$hometown', min_age: {$min: '$age'}, count: {$sum: 1}}})

注意: 
    _id后面的值,表示按照什么分组,格式'$字段'
    count, avg_count是自定义的字段
    表达式的值是'$字段'

Group by null

将集合中所用文档分为一组,即该集合就是一个组
# 求学生的总量和平均年龄
db.stu.aggregate({$group: {_id: null, count:{$sum: 1}, avg_age:{$avg: '$age'}}})

补充


# 插入数据

db.test.insert({country: "china", province: "sh", userid: "a"})
db.test.insert({country: "china", province: "sh", userid: "b"})
db.test.insert({country: "china", province: "sh", userid: "a"})
db.test.insert({country: "china", province: "sh", userid: "c"})
db.test.insert({country: "china", province: "bj", userid: "da"})
db.test.insert({country: "china", province: "bj", userid: "fa"})

# 1.去重
能够同时按照多个键进行分组,若文档中的每个字段都进行分组,那么可以实现去重的功能
db.test.aggregate({$group: {_id: {country: '$country', province: '$province'}}})
# 2.取字典嵌套的字典中的值 
_id: {contry: '$_id.country'}
例子
db.test.aggregate(
{$group: {_id: {country: '$country', province: '$province', userid: '$userid'}}},  
{$group: {_id: {country: '$_id.country', province: '$_id.province'}, count: {$sum: 1}}}, 
{$project: {country: '$_id.country', province: '$_id.province', count: '$count', _id: 0}}
)

2、$project


作用:修改输入文档的结构,如重命名、增加(显示)、删除(隐藏)字段,创建计算结果
1.显示和隐藏
格式: 
db.集合名称.aggregate({$project: {_id: 0, 字段:1}})
值为0,是隐藏
值为1,是显示
示例
db.stu.aggregate({$project: {_id: 0, name: 1, hometown: 1, age: 1, gender: 1}})
注意: 显示、隐藏字段和投影差不多
2.重命名
例子
db.stu.aggregate({$group: {_id: '$gender', count: {$sum: 1}, avg: {$avg: '$age'}}}, {$project: {_id: 0,gender: '$_id', counter: '$count', avg_age: '$avg'}})
注意: 
重命名字段格式 {新的字段名: '$旧的字段名称'}
管道符之间用逗号隔

3、$match


作用: 用于过滤数据,只输出符合条件的文档
注意: match是管道命令,能将结果交给下一个管道,find不可以
例子
db.stu.aggregate({$match: {age: {$lte: 18}}})
# 过滤->分组->重命名、显示
db.stu.aggregate({$match: {age: {$lte: 18}}}, {$group: {_id: '$gender', count: {$sum: 1}}}, {$project: {gender: '$_id', _id: 0, count: 1}})

4、$limit和$skip


$limit
限制聚合管道返回的文档数
例子
db.stu.aggregate({$limit: 2})

$skip
跳过指定数量的聚合管道文档。并返回剩下的文档
例子
db.stu.aggregate({$skip: 2})
db.stu.aggregate({$limit: 2}, {$skip: 3})
注意顺序:先写skip,再写limit

5、$unwind


# unwind 解开,松开
作用: 将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值
格式:
db.集合名称.aggregate({$unwind: '$字段名称'})
例子
db.t2.insert({_id: 1, item:'t-shirt', size: ['S', 'M', 'L']})
db.t2.aggregate({$unwind: '$size'})
结果:
{ "_id" : 1, "item" : "t-shirt", "size" : "S" }
{ "_id" : 1, "item" : "t-shirt", "size" : "M" }
{ "_id" : 1, "item" : "t-shirt", "size" : "L" }

# 补充

db.集合名称.aggregate({
    $unwind: {
        path: '$字段名称',
        preserveNullAndEmptyArrays: <boolean>  # 防止数据丢失
    }
})
属性preserveNullAndEmptyArrays值
为false表示抛弃属性值为空的文档
为true表示保留属性值为空的文档

例子
db.t3.aggregate({$unwind: {path: '$size', preserveNullAndEmptyArrays: false}})

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK