mongdb的聚合管道
我们先介绍一下 MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进行一系列操作,例如,求最大值、最小值、平均值,求和等操作。聚合操作还能够对记录进行复杂的操作,主要用于数理统计和数据挖掘。在 MongoDB 中,聚合操作的输入是集合中的文档,输出可以是一个文档,也可以是多条文档。在管道查询过程中,上次查询的结果可以为这次查询的条件。
使用阶段操作符之前,我们先看一下 article 集合中的文档列表,也就是范例中用到的数据。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1.1.1、$project
作用
修改文档的结构,可以用来重命名、增加或删除文档中的字段。
范例1
只返回文档中 title 和 author 字段
|
1 2 3 4 |
|
因为字段 _id 是默认显示的,这里必须用 _id:0 把字段_id过滤掉。
范例2
把文档中 pages 字段的值都增加10。并重命名成 newPages 字段。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
其中,$add 是 加 的意思,是算术类型表达式操作符,具体表达式操作符,下面会讲到。
1.1.2、$match
作用
用于过滤文档。用法类似于 find() 方法中的参数。
范例
查询出文档中 pages 字段的值大于等于5的数据。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
注:
- 在 $match 中不能使用 $where 表达式操作符
- 如果 $match 位于管道的第一个阶段,可以利用索引来提高查询效率
- $match 中使用 $text 操作符的话,只能位于管道的第一阶段
- $match 尽量出现在管道的最前面,过滤出需要的数据,在后续的阶段中可以提高效率。
1.1.3、$group
作用
将集合中的文档进行分组,可用于统计结果。
范例
从 article 中得到每个 author 的文章数,并输入 author 和对应的文章数。
|
1 2 3 4 5 6 7 8 9 |
|
1.1.4、$sort
作用
将集合中的文档进行排序。
范例
让集合 article 以 pages 升序排列
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
如果以降序排列,则设置成 "pages": -1
1.1.5、$limit
作用
限制返回的文档数量
范例
返回集合 article 中前两条文档
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1.1.6、$skip
作用
跳过指定数量的文档,并返回余下的文档。
范例
跳过集合 article 中一条文档,输出剩下的文档
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1.1.7、$unwind
作用
将文档中数组类型的字段拆分成多条,每条文档包含数组中的一个值。
范例
把集合 article 中 title="MongoDB Aggregate" 的 tags 字段拆分
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
注:
- $unwind 参数数组字段为空或不存在时,待处理的文档将会被忽略,该文档将不会有任何输出
- $unwind 参数不是一个数组类型时,将会抛出异常
- $unwind 所作的修改,只用于输出,不能改变原文档
1.2、表达式操作符
表达式操作符有很多操作类型,其中最常用的有布尔管道聚合操作、集合操作、比较聚合操作、算术聚合操作、字符串聚合操作、数组聚合操作、日期聚合操作、条件聚合操作、数据类型聚合操作等。每种类型都有很多用法,这里就不一一举例了。
1.2.1、布尔管道聚合操作(Boolean Aggregation Operators)
| 名称 | 说明 |
|---|---|
$and |
Returns true only when all its expressions evaluate to true. Accepts any number of argument expressions. |
$or |
Returns true when any of its expressions evaluates to true. Accepts any number of argument expressions. |
$not |
Returns the boolean value that is the opposite of its argument expression. Accepts a single argument expression. |
范例
假如有一个集合 mycol
|
1 2 3 4 5 |
|
确定 qty 是否大于250或者小于200
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1.2.2、集合操作(Set Operators)
用于集合操作,求集合的并集、交集、差集运算。
| 名称 | 说明 |
|---|---|
$setEquals |
Returns true if the input sets have the same distinct elements. Accepts two or more argument expressions. |
$setIntersection |
Returns a set with elements that appear in all of the input sets. Accepts any number of argument expressions. |
$setUnion |
Returns a set with elements that appear in any of the input sets. Accepts any number of argument expressions. |
$setDifference |
Returns a set with elements that appear in the first set but not in the second set; i.e. performs a relative complement of the second set relative to the first. Accepts exactly two argument expressions. |
$setIsSubset |
Returns true if all elements of the first set appear in the second set, including when the first set equals the second set; i.e. not a strict subset. Accepts exactly two argument expressions. |
$anyElementTrue |
Returns true if any elements of a set evaluate to true; otherwise, returns false. Accepts a single argument expression. |
$allElementsTrue |
Returns true if no element of a set evaluates to false, otherwise, returns false. Accepts a single argument expression. |
范例
假如有一个集合 mycol
|
1 2 3 4 5 6 7 8 9 |
|
求出集合 mycol 中 A 和 B 的交集
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1.2.3、比较聚合操作(Comparison Aggregation Operators)
| 名称 | 说明 |
|---|---|
$cmp |
Returns: 0 if the two values are equivalent, 1 if the first value is greater than the second, and -1 if the first value is less than the second. |
$eq |
Returns true if the values are equivalent. |
$gt |
Returns true if the first value is greater than the second. |
$gte |
Returns true if the first value is greater than or equal to the second. |
$lt |
Returns true if the first value is less than the second. |
$lte |
Returns true if the first value is less than or equal to the second. |
$ne |
Returns true if the values are not equivalent. |
这里就不举例了,之前的例子有用到过。
1.2.4、算术聚合操作(Arithmetic Aggregation Operators)
| 名称 | 说明 |
|---|---|
$abs |
Returns the absolute value of a number. |
$add |
Adds numbers to return the sum, or adds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date. |
$ceil |
Returns the smallest integer greater than or equal to the specified number. |
$divide |
Returns the result of dividing the first number by the second. Accepts two argument expressions. |
$exp |
Raises e to the specified exponent. |
$floor |
Returns the largest integer less than or equal to the specified number. |
$ln |
Calculates the natural log of a number. |
$log |
Calculates the log of a number in the specified base. |
$log10 |
Calculates the log base 10 of a number. |
$mod |
Returns the remainder of the first number divided by the second. Accepts two argument expressions. |
$multiply |
Multiplies numbers to return the product. Accepts any number of argument expressions. |
$pow |
Raises a number to the specified exponent. |
$sqrt |
Calculates the square root. |
$subtract |
Returns the result of subtracting the second value from the first. If the two values are numbers, return the difference. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number. |
$trunc |
Truncates a number to its integer. |
范例
假如有一个集合 mycol
|
1 2 3 4 |
|
求集合 mycol 中 start 减去 end 的绝对值
|
1 2 3 4 5 6 7 8 9 |
|
1.2.5、字符串聚合操作(String Aggregation Operators)
| 名称 | 说明 |
|---|---|
$concat |
Concatenates any number of strings. |
$indexOfBytes |
Searches a string for an occurence of a substring and returns the UTF-8 byte index of the first occurence. If the substring is not found, returns -1. |
$indexOfCP |
Searches a string for an occurence of a substring and returns the UTF-8 code point index of the first occurence. If the substring is not found, returns -1. |
$split |
Splits a string into substrings based on a delimiter. Returns an array of substrings. If the delimiter is not found within the string, returns an array containing the original string. |
$strLenBytes |
Returns the number of UTF-8 encoded bytes in a string. |
$strLenCP |
Returns the number of UTF-8 code points in a string. |
$strcasecmp |
Performs case-insensitive string comparison and returns: 0 if two strings are equivalent, 1 if the first string is greater than the second, and -1 if the first string is less than the second. |
$substr |
Deprecated. Use $substrBytes or $substrCP. |
$substrBytes |
Returns the substring of a string. Starts with the character at the specified UTF-8 byte index (zero-based) in the string and continues for the specified number of bytes. |
$substrCP |
Returns the substring of a string. Starts with the character at the specified UTF-8 code point (CP) index (zero-based) in the string and continues for the number of code points specified. |
$toLower |
Converts a string to lowercase. Accepts a single argument expression. |
$toUpper |
Converts a string to uppercase. Accepts a single argument expression. |
范例
假如有一个集合 mycol
|
1 2 3 4 5 6 7 |
|
以 ',' 分割集合 mycol 中字符串city的值,用 $unwind 拆分成多个文档,匹配出城市名称只有两个字母的城市,并求和各个城市中 qty 的值,最后以降序排序。
|
1 2 3 4 5 6 7 8 9 10 |
|
1.2.6、数组聚合操作(Array Aggregation Operators)
| 名称 | 说明 |
|---|---|
$arrayElemAt |
Returns the element at the specified array index. |
$concatArrays |
Concatenates arrays to return the concatenated array. |
$filter |
Selects a subset of the array to return an array with only the elements that match the filter condition. |
$indexOfArray |
Searches an array for an occurence of a specified value and returns the array index of the first occurence. If the substring is not found, returns -1. |
$isArray |
Determines if the operand is an array. Returns a boolean. |
$range |
Outputs an array containing a sequence of integers according to user-defined inputs. |
$reverseArray |
Returns an array with the elements in reverse order. |
$reduce |
Applies an expression to each element in an array and combines them into a single value. |
$size |
Returns the number of elements in the array. Accepts a single expression as argument. |
$slice |
Returns a subset of an array. |
$zip |
Merge two lists together. |
$in |
Returns a boolean indicating whether a specified value is in an array. |
范例
假如有一个集合 mycol
|
1 2 3 4 |
|
求出集合 mycol 中 favorites 的第一项和最后一项
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1.2.7、日期聚合操作(Date Aggregation Operators)
| 名称 | 说明 |
|---|---|
$dayOfYear |
Returns the day of the year for a date as a number between 1 and 366 (leap year). |
$dayOfMonth |
Returns the day of the month for a date as a number between 1 and 31. |
$dayOfWeek |
Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday). |
$year |
Returns the year for a date as a number (e.g. 2014). |
$month |
Returns the month for a date as a number between 1 (January) and 12 (December). |
$week |
Returns the week number for a date as a number between 0 (the partial week that precedes the first Sunday of the year) and 53 (leap year). |
$hour |
Returns the hour for a date as a number between 0 and 23. |
$minute |
Returns the minute for a date as a number between 0 and 59. |
$second |
Returns the seconds for a date as a number between 0 and 60 (leap seconds). |
$millisecond |
Returns the milliseconds of a date as a number between 0 and 999. |
$dateToString |
Returns the date as a formatted string. |
$isoDayOfWeek |
Returns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday). |
$isoWeek |
Returns the week number in ISO 8601 format, ranging from 1 to 53. Week numbers start at 1 with the week (Monday through Sunday) that contains the year’s first Thursday. |
$isoWeekYear |
Returns the year number in ISO 8601 format. The year starts with the Monday of week 1 (ISO 8601) and ends with the Sunday of the last week (ISO 8601). |
范例
假如有一个集合 mycol
|
1 |
|
得到集合 mycol 中 date 字段的相关日期值
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
1.2.8、条件聚合操作(Conditional Aggregation Operators)
| 名称 | 说明 |
|---|---|
$cond |
A ternary operator that evaluates one expression, and depending on the result, returns the value of one of the other two expressions. Accepts either three expressions in an ordered list or three named parameters. |
$ifNull |
Returns either the non-null result of the first expression or the result of the second expression if the first expression results in a null result. Null result encompasses instances of undefined values or missing fields. Accepts two expressions as arguments. The result of the second expression can be null. |
$switch |
Evaluates a series of case expressions. When it finds an expression which evaluates to true, $switch executes a specified expression and breaks out of the control flow. |
范例
假如有一个集合 mycol
|
1 2 3 |
|
如果集合 mycol 中 qty 字段值大于等于250,则返回30,否则返回20
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1.2.9、数据类型聚合操作(Data Type Aggregation Operators)
| 名称 | 说明 |
|---|---|
$type |
Return the BSON data type of the field. |
范例
假如有一个集合 mycol
|
1 2 3 4 5 6 |
|
获取文档中 a 字段的数据类型
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1.3、聚合管道优化
默认情况下,整个集合作为聚合管道的输入,为了提高处理数据的效率,可以使用一下策略:
- 将 $match 和 $sort 放到管道的前面,可以给集合建立索引,来提高处理数据的效率。
- 可以用 $match、$limit、$skip 对文档进行提前过滤,以减少后续处理文档的数量。
当聚合管道执行命令时,MongoDB 也会对各个阶段自动进行优化,主要包括以下几个情况:
- $sort + $match 顺序优化
如果 $match 出现在 $sort 之后,优化器会自动把 $match 放到 $sort 前面
2. $skip + $limit 顺序优化
如果 $skip 在 $limit 之后,优化器会把 $limit 移动到 $skip 的前面,移动后 $limit的值等于原来的值加上 $skip 的值。
例如:移动前:{$skip: 10, $limit: 5},移动后:{$limit: 15, $skip: 10}
1.4、聚合管道使用限制
对聚合管道的限制主要是对 返回结果大小 和 内存 的限制。
返回结果大小
聚合结果返回的是一个文档,不能超过 16M,从 MongoDB 2.6版本以后,返回的结果可以是一个游标或者存储到集合中,返回的结果不受 16M 的限制。
内存
聚合管道的每个阶段最多只能用 100M 的内存,如果超过100M,会报错,如果需要处理大数据,可以使用 allowDiskUse 选项,存储到磁盘上。
2、单目的聚合操作
单目的聚合命令,常用的:count()、distinct(),与聚合管道相比,单目的聚合操作更简单,使用非常频繁。先通过 distinct() 看一下工作流程

distinct() 的作用是去重。而 count() 是求文档的个数。
下面用 count() 方法举例说明一下
范例
求出集合 article 中 time 值大于 2017-04-09 的文档个数
|
1 2 |
|
这个语句等价于
|
1 |
|
参考:https://blog.csdn.net/qq_37193537/article/details/82388638
mongdb的聚合管道的更多相关文章
- 【翻译】MongoDB指南/聚合——聚合管道
[原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...
- MongoDB 聚合管道(Aggregation Pipeline)
管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...
- MongoDB学习笔记——聚合操作之聚合管道(Aggregation Pipeline)
MongoDB聚合管道 使用聚合管道可以对集合中的文档进行变换和组合. 管道是由一个个功能节点组成的,这些节点用管道操作符来进行表示.聚合管道以一个集合中的所有文档作为开始,然后这些文档从一个操作节点 ...
- MongoDB聚合管道(Aggregation Pipeline)
参考聚合管道简介 聚合管道 聚合管道是基于数据处理管道模型的数据聚合框架.文档进入一个拥有多阶段(multi-stage)的管道,并被管道转换成一个聚合结果.最基本的管道阶段提供了跟查询操作类似的过滤 ...
- MongoDB基础教程系列--第七篇 MongoDB 聚合管道
在讲解聚合管道(Aggregation Pipeline)之前,我们先介绍一下 MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进行一系列操作,例如,求最 ...
- 【mongoDB查询进阶】聚合管道(二) -- 阶段操作符
https://segmentfault.com/a/1190000010826809 什么是管道操作符(Aggregation Pipeline Operators) mongoDB有4类操作符用于 ...
- 【mongoDB查询进阶】聚合管道(一) -- 初识
https://segmentfault.com/a/1190000010618355 前言:一般查询可以通过find方法,但如果是比较复杂的查询或者数据统计的话,find可能就无能为力了,这时也许你 ...
- 第14章:MongoDB-聚合操作--聚合管道
① 聚合管道是MongoDB2.2版本引入的新功能.它由阶段(Stage)组成,文档在一个阶段处理完毕后,聚合管道会把处理结果传到下一个阶段. 每个阶段用阶段操作符(Stage Operators)定 ...
- MongoDB聚合管道
通过上一篇文章中,认识了MongoDB中四个聚合操作,提供基本功能的count.distinct和group,还有可以提供强大功能的mapReduce. 在MongoDB的2.2版本以后,聚合框架中多 ...
随机推荐
- 读<css世界>笔记之img标签
Web开发时,为了节约带宽以及提高加载性能,首屏以下的图片就会通过滚屏加载的方式异步加载,然后这个即将被异步加载的图片为了布局稳健,体验良好,往往会使用一张透明的图片占位,如: <img src ...
- SQL Server Mobile/Compact Edition 简单介绍
除了SQL Server Express,SQL Server还有个更轻量级的版本:SQL Server Compact Edition,容易让人想起Windows Compact Edition ( ...
- Python学习---django下的Session操作 180205
和Cookie一样,都是用来进行用户认证.不同的是,Cookie可以吧明文/密文的信息都会KV返回给客户段,但是session可以吧用户的Value[敏感信息]保存在服务器端,安全. Django中默 ...
- [EffectiveC++]item24:若所有参数皆需类型转换,请为此采用non-member函数
Declare non-member functions when type conversions should apply to all parameters. 104页 只有当参数被列于参数列( ...
- myeclipse 2013破解注册图文教程
以下这个试过有效 http://www.33lc.com/article/10792.html
- 美团2018年CodeM大赛-初赛B轮 B 配送(最短路)
美团2018年CodeM大赛-初赛B轮 B 配送 题意 题解 对于每个任务,只要从上个任务的终点出发即可. 时间.地点很少,可以算出每个地点-时间的最小花费. 以题目描述的起点终点起始结束时间建图,很 ...
- boost编译
从boost官网( http://www.boost.org )上下载最新的boost版本,现在最新是1.64版本,解压到自定义目录(我解压到了E盘E:\boost_1_64_0\,最终的目录结构是E ...
- metasploit 渗透测试笔记(meterpreter篇)
0x01 背景 meterpreter作为后渗透模块有多种类型,并且命令由核心命令和扩展库命令组成,极大的丰富了攻击方式. 需要说明的是meterpreter在漏洞利用成功后会发送第二阶段的代码和me ...
- 组合数取模方法总结(Lucas定理介绍)
1.当n,m都很小的时候可以利用杨辉三角直接求. C(n,m)=C(n-1,m)+C(n-1,m-1): 2.n和m较大,但是p为素数的时候 Lucas定理是用来求 c(n,m) mod p,p为素数 ...
- Java50道经典习题-程序13 根据条件求数字
题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?分析:完全平方数:如果一个数能是由两个相同的数相乘的结果,那么这个数就是完全平方数,例如:9==3*3: ...