mongo与mysql聚合类比
SQL 操作/函数 | mongodb聚合操作 |
---|---|
where | $match |
group by | $group |
having | $match |
select | $project |
order by | $sort |
limit | $limit |
sum() | $sum |
count() | $sum |
join | $lookup(v3.2 新增) |
1
2
3
4
5
6
7
8{ cust_id: "abc123", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: 'A', price: 50, items: [ { sku: "xxx", qty: 25, price: 1 }, { sku: "yyy", qty: 25, price: 1 } ] }
1. 统计orders表所有记录
1
2
3
4
5
6
7
8
9
10
11db.orders.aggregate( [ { $group: { _id: null, count: { $sum: 1 } } } ]) 类似mysql: SELECT COUNT(*) AS count FROM orders
2.对orders表计算所有price求和
1
2
3
4
5
6
7
8
9
10
11db.orders.aggregate( [ { $group: { _id: null, count: { $sum: "$price" } } } ]) 类似mysql; SELECT SUM(price) AS total FROM orders
3.对每一个唯一的cust_id, 计算price总和
1
2
3
4
5
6
7
8
9
10
11
12
13
14db.orders.aggregate([ { "$group": { _id: "$cust_id", total: { $sum: "$price" } } } ]) 类似mysql: SELECT cust_id, SUM(price) AS total FROM orders GROUP BY cust_id
4.对每一个唯一对cust_id和ord_date分组,计算price总和,不包括日期的时间部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23db.orders.aggregate([ { "$group": { _id: { cust_id: "$cust_id", ord_date: { month: { $month: "$ord_date" }, day: { $dayOfMonth: "$ord_date" }, year: { $year: "$ord_date" } } }, total: { $sum: "$price" } } } ]) 类似mysql: SELECT cust_id, ord_date, SUM(price) AS total FROM orders GROUP BY cust_id, ord_date
5.对于有多个记录的cust_id,返回cust_id和对应的数量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16db.orders.aggregate([ { "$group": { _id: "$cust_id", count: { $sum : 1} } }, { $match: { count : { $gt: 1 } } } ]) 类似mysql: SELECT cust_id, count(*) FROM orders GROUP BY cust_id HAVING count(*) > 1
6.对每个唯一的cust_id和ord_date分组,计算价格总和,并只返回price总和大于250的记录,且排除日期的时间部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25db.orders.aggregate([ { "$group": { _id: { cust_id: "$cust_id", ord_date: { month: { $month: "$ord_date" }, day: { $dayOfMonth: "$ord_date" }, year: { $year: "$ord_date" } } }, total: { $sum: "$price" } } }, { $match: { total : { $gt: 250 } } } ]) 类似mysql: SELECT cust_id, ord_date, SUM(price) AS total FROM orders GROUP BY cust_id, ord_date HAVING total > 250
7.对每个唯一的cust_id且status=A,计算price总和
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16db.orders.aggregate([ { $match: { status: "A" } }, { "$group": { _id: "$cust_id", total: { $sum: "$price" } } } ]) 类似mysql: SELECT cust_id, SUM(price) as total FROM orders WHERE status = 'A' GROUP BY cust_id
8.对每个唯一的cust_id且status=A,计算price总和并且只返回price总和大于250的记录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19db.orders.aggregate( [ { $match: { status: 'A' } }, { $group: { _id: "$cust_id", total: { $sum: "$price" } } }, { $match: { total: { $gt: 250 } } } ] ) 类似mysql: SELECT cust_id, SUM(price) as total FROM orders WHERE status = 'A' GROUP BY cust_id HAVING total > 250
9.对于每个唯一的cust_id,将与orders相关联的相应订单项order_lineitem的qty字段进行总计
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17db.orders.aggregate( [ { $unwind: "$items" }, { $group: { _id: "$cust_id", qty: { $sum: "$items.qty" } } } ] ) 类似mysql: SELECT cust_id, SUM(li.qty) as qty FROM orders o, order_lineitem li WHERE li.order_id = o.id GROUP BY cust_id
10.统计不同cust_id和ord_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
27db.orders.aggregate( [ { $group: { _id: { cust_id: "$cust_id", ord_date: { month: { $month: "$ord_date" }, day: { $dayOfMonth: "$ord_date" }, year: { $year: "$ord_date"} } } } }, { $group: { _id: null, count: { $sum: 1 } } } ] ) 类似mysql: SELECT COUNT(*) FROM (SELECT cust_id, ord_date FROM orders GROUP BY cust_id, ord_date) as DerivedTable
Aggregate简介
db.collection.aggregate() 可以用多个构件创建一个管道,对于一连串的文档进行处理。这些构件包括:筛选操作的match、映射操作的project、分组操作的group、排序操作的sort、限制操作的limit、和跳过操作的skip。
db.collection.aggregate()使用了MongoDB内置的原生操作,聚合效率非常高,支持类似于SQL Group By操作的功能,而不再需要用户编写自定义的JavaScript例程。
每个阶段管道限制为100MB的内存。如果一个节点管道超过这个极限,MongoDB将产生一个错误。为了能够在处理大型数据集,可以设置allowDiskUse为true来在聚合管道节点把数据写入临时文件。这样就可以解决100MB的内存的限制。
db.collection.aggregate()可以作用在分片集合,但结果不能输在分片集合,MapReduce可以 作用在分片集合,结果也可以输在分片集合。
db.collection.aggregate()方法可以返回一个指针(cursor),数据放在内存中,直接操作。跟Mongo shell 一样指针操作。
db.collection.aggregate()输出的结果只能保存在一个文档中,BSON Document大小限制为16M。可以通过返回指针解决,版本2.6中后面:DB.collect.aggregate()方法返回一个指针,可以返回任何结果集的大小。
Aggregate语法
1db.collection.aggregate(pipeline, options)1
参数 | 类型 | 描述 |
---|---|---|
pipeline | array | 一系列数据聚合操作或阶段。详见聚合管道操作符。在版本2.6中更改:该方法仍然可以将流水线阶段作为单独的参数接受,而不是作为数组中的元素;但是,如果不将管道指定为数组,则不能指定options参数 |
options document | 可选 | aggregate()传递给聚合命令的其他选项。2.6版中的新增功能:仅当将管道指定为数组时才可用。 |
aggregate常用pipeline stage介绍
$count
1{ $count: <string> }1
1
2
3
4db.collection.aggregate( [ { $group: { _id: null, myCount: { $sum: 1 } } }, #这里myCount自定义,相当于mysql的select count(*) as myCount { $project: { _id: 0 } } # 返回不显示_id字段 ] )
1
2
3
4
5
6{ "_id" : 1, "subject" : "History", "score" : 88 } { "_id" : 2, "subject" : "History", "score" : 92 } { "_id" : 3, "subject" : "History", "score" : 97 } { "_id" : 4, "subject" : "History", "score" : 71 } { "_id" : 5, "subject" : "History", "score" : 79 } { "_id" : 6, "subject" : "History", "score" : 83 }
1
2
3
4
5
6
7
8
9
10> db.test.aggregate([ ... { ... $match: { "score": { $gt: 80 } } ... }, ... { ... $count: "passing_scores" ... } ... ]) { "passing_scores" : 4 } >
$group
1{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }1
_id字段是必填的;但是,可以指定_id值为null来为整个输入文档计算累计值
剩余的计算字段是可选的,并使用<accumulator>运算符进行计算
_id和<accumulator>表达式可以接受任何有效的表达式
名称 | 描述 | 类比sql |
---|---|---|
$avg | 计算均值 | avg |
$first | 返回每组第一个文档,如果有排序,按照排序,如果没有按照默认的存储的顺序的第一个文档 | limit 0,1 |
$last | 返回每组最后一个文档,如果有排序,按照排序,如果没有按照默认的存储的顺序的最后个文档 | - |
$max | 根据分组,获取集合中所有文档对应值得最大值 | max |
$min | 根据分组,获取集合中所有文档对应值得最小值 | min |
$push | 将指定的表达式的值添加到一个数组中 | - |
$addToSet | 将表达式的值添加到一个集合中(无重复值,无序) | - |
$sum | 计算总和 | sum |
$stdDevPop | 返回输入值的总体标准偏差(population standard deviation) | - |
$stdDevSamp | 返回输入值的样本标准偏差(the sample standard deviation) | - |
“$addToSet”:expr,如果当前数组中不包含expr,那就将它添加到数组中。
“$push”:expr,不管expr是什么只,都将它添加到数组中。返回包含所有值的数组。
1
2
3
4
5{ "_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") }
以下汇总操作使用$group阶段按月份,日期和年份对文档进行分组,并计算total price和average quantity,并计算每个组的文档数量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18> db.test.aggregate([ ... { ... $group: { ... _id: { ... month: { $month: "$date" }, ... day: { $dayOfMonth: "$date" }, ... year: { $year: "$date" } ... }, ... total: { $sum: "$price" }, ... average: { $avg: "$quantity" }, ... count: { $sum: 1 } ... } ... } ... ]) { "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "total" : 15, "average" : 15, "count" : 2 } { "_id" : { "month" : 3, "day" : 15, "year" : 2014 }, "total" : 5, "average" : 10, "count" : 1 } { "_id" : { "month" : 3, "day" : 1, "year" : 2014 }, "total" : 30, "average" : 1.5, "count" : 2 } >
group null , 以下聚合操作将指定组_id为null,计算集合中所有文档的总价格和平均数量以及计数:
1
2
3
4
5
6
7
8
9
10
11
12> db.test.aggregate([ ... { ... $group: { ... _id: null, ... total: { $sum: "$price" }, ... average: { $avg: "$quantity" }, ... count: { $sum: 1 } ... } ... } ... ]) { "_id" : null, "total" : 50, "average" : 8.6, "count" : 5 } >
查询distinct values
1
2
3
4
5
6
7
8
9
10
11> db.test.aggregate([ ... { ... $group: { ... _id: "$item" ... } ... } ... ]) { "_id" : "xyz" } { "_id" : "jkl" } { "_id" : "abc" } >
数据转换
将集合中的数据按price分组转换成item数组
1
2
3
4
5
6
7
8
9
10
11
12> db.test.aggregate([ ... { ... $group: { ... _id: "$price", ... items: { $push: "$item" } ... } ... } ... ]) { "_id" : 5, "items" : [ "xyz", "xyz" ] } { "_id" : 20, "items" : [ "jkl" ] } { "_id" : 10, "items" : [ "abc", "abc" ] } >
下面聚合操作实用系统变量$$ROOT按item对文档进行分组,生成的文档不得超过BSON文档大小限制。
1
2
3
4
5
6
7
8
9
10
11
12> db.test.aggregate([ ... { ... $group: { ... _id: "$price", ... items: { $push: "$$ROOT" } ... } ... } ... ]) { "_id" : 5, "items" : [ { "_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" : 20, "items" : [ { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") } ] } { "_id" : 10, "items" : [ { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") }, { "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") } ] } >
$match
1{ $match: { <query> } }1
不能在match查询中使用作为聚合管道的一部分。
要在match阶段使用text,$match阶段必须是管道的第一阶段。
视图不支持文本搜索。
1
2
3
4
5
6
7{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 } { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 } { "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : 60, "views" : 1000 } { "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : 55, "views" : 5000 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : 60, "views" : 50 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b25a"), "author" : "li", "score" : 94, "views" : 999 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b25b"), "author" : "ty", "score" : 95, "views" : 1000 }
使用 $match做简单的匹配查询
1
2
3
4
5
6
7
8> db.test.aggregate([ ... { ... $match: { author: "dave" } ... } ... ]) { "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 } { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 } >
使用match管道选择要处理的文档,然后将结果输出到group管道以计算文档的计数:
1
2
3
4
5
6
7
8
9
10
11> db.test.aggregate([ ... { ... $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } ... }, ... { ... $group: { _id: null, count: { $sum: 1 } } ... } ... ]) { "_id" : null, "count" : 5 } >
$unwind
1{ $unwind: <field path> }1
1
2
3
4
5
6
7
8{ $unwind: { path: <field path>, includeArrayIndex: <string>, #可选,一个新字段的名称用于存放元素的数组索引。该名称不能以$开头。 preserveNullAndEmptyArrays: <boolean> #可选,default :false,若为true,如果路径为空,缺少或为空数组,则$unwind输出文档 } }
示例数据1:
1{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }1
1
2
3
4
5
6
7> db.test.aggregate([ ... { $unwind : "$sizes" } ... ]) { "_id" : 1, "item" : "ABC1", "sizes" : "S" } { "_id" : 1, "item" : "ABC1", "sizes" : "M" } { "_id" : 1, "item" : "ABC1", "sizes" : "L" } >
再如下示例数据:
1
2
3
4
5{ "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] } { "_id" : 2, "item" : "EFG", "sizes" : [ ] } { "_id" : 3, "item" : "IJK", "sizes": "M" } { "_id" : 4, "item" : "LMN" } { "_id" : 5, "item" : "XYZ", "sizes" : null }
1
2
3
4
5
6
7
8
9
10
11
12
13> db.test.aggregate([ ... { ... $unwind: { ... path: "$sizes", ... includeArrayIndex: "arrayIndex" ... } ... } ... ]) { "_id" : 1, "item" : "ABC", "sizes" : "S", "arrayIndex" : NumberLong(0) } { "_id" : 1, "item" : "ABC", "sizes" : "M", "arrayIndex" : NumberLong(1) } { "_id" : 1, "item" : "ABC", "sizes" : "L", "arrayIndex" : NumberLong(2) } { "_id" : 3, "item" : "IJK", "sizes" : "M", "arrayIndex" : null } >
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16> db.test.aggregate([ ... { ... $unwind: { ... path: "$sizes", ... preserveNullAndEmptyArrays: true ... } ... } ... ]) { "_id" : 1, "item" : "ABC", "sizes" : "S" } { "_id" : 1, "item" : "ABC", "sizes" : "M" } { "_id" : 1, "item" : "ABC", "sizes" : "L" } { "_id" : 2, "item" : "EFG" } { "_id" : 3, "item" : "IJK", "sizes" : "M" } { "_id" : 4, "item" : "LMN" } { "_id" : 5, "item" : "XYZ", "sizes" : null } >
$project
1{ $project: { <specification(s)> } }1
1
2
3"contact.address.country": <1 or 0 or expression> 或 contact: { address: { country: <1 or 0 or expression> } }
1
2
3
4
5> db.test.aggregate([ ... { $project: { title : 1, author: 1 } } ... ]) { "_id" : 1, "title" : "abc123", "author" : { "last" : "zzz", "first" : "aaa" } } >
_id字段默认包含在内。要从$project阶段的输出文档中排除_id字段,请在project文档中将_id字段设置为0来指定排除_id字段。
1
2
3
4
5> db.test.aggregate([ ... { $project: { _id: 0, title : 1, author: 1 } } ... ]) { "title" : "abc123", "author" : { "last" : "zzz", "first" : "aaa" } } >
1db.test.aggregate( [ { $project : { "lastModified": 0 } } ] )1
1
2
3
4
5> db.test.aggregate([ ... ... ... { $project: { "author.first" : 0, "lastModified" : 0 } } ... ]) { "_id" : 1, "title" : "abc123", "isbn" : "0001122223334", "author" : { "last" : "zzz" }, "copies" : 5 } >
1db.test.aggregate( [ { $project: { "author": { "first": 0}, "lastModified" : 0 } } ] )1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24{ "_id" : 1, title: "abc123", isbn: "0001122223334", author: { last: "zzz", first: "aaa" }, copies: 5, lastModified: "2016-07-28" } { "_id" : 2, title: "Baked Goods", isbn: "9999999999999", author: { last: "xyz", first: "abc", middle: "" }, copies: 2, lastModified: "2017-07-21" } { "_id" : 3, title: "Ice Cream Cakes", isbn: "8888888888888", author: { last: "xyz", first: "abc", middle: "mmm" }, copies: 5, lastModified: "2017-07-22" }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20> db.test.aggregate([ ... ... { ... ... $project: { ... ... title: 1, ... ... "author.first": 1, ... ... "author.last": 1, ... ... "author.middle": { ... ... $cond: { ... ... if: { $eq: [ "", "$author.middle" ] }, ... ... then: "$$REMOVE", ... ... else: "$author.middle" ... ... } ... ... } ... ... } ... ... } ... ... ]) { "_id" : 1, "title" : "abc123", "author" : { "last" : "zzz", "first" : "aaa" } } { "_id" : 2, "title" : "Baked Goods", "author" : { "last" : "xyz", "first" : "abc" } } { "_id" : 3, "title" : "Ice Cream Cakes", "author" : { "last" : "xyz", "first" : "abc", "middle" : "mmm" } } >
1
2{ _id: 1, user: "1234", stop: { title: "book1", author: "xyz", page: 32 } } { _id: 2, user: "7890", stop: [ { title: "book2", author: "abc", page: 5 }, { title: "book3", author: "ijk", page: 100 } ] }12
1
2
3
4> db.test.aggregate([ { $project: { "stop.title": 1 } } ]) { "_id" : 1, "stop" : { "title" : "book1" } } { "_id" : 2, "stop" : [ { "title" : "book2" }, { "title" : "book3" } ] } >
1
2
3
4
5
6
7{ "_id" : 1, title: "abc123", isbn: "0001122223334", author: { last: "zzz", first: "aaa" }, copies: 5 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20> db.test.aggregate( ... [ ... { ... $project: { ... title: 1, ... isbn: { ... prefix: { $substr: [ "$isbn", 0, 3 ] }, ... group: { $substr: [ "$isbn", 3, 2 ] }, ... publisher: { $substr: [ "$isbn", 5, 4 ] }, ... title: { $substr: [ "$isbn", 9, 3 ] }, ... checkDigit: { $substr: [ "$isbn", 12, 1] } ... }, ... lastName: "$author.last", ... copiesSold: "$copies" ... } ... } ... ] ... ) { "_id" : 1, "title" : "abc123", "isbn" : { "prefix" : "000", "group" : "11", "publisher" : "2222", "title" : "333", "checkDigit" : "4" }, "lastName" : "zzz", "copiesSold" : 5 } >
1{ "_id" : ObjectId("55ad167f320c6be244eb3b95"), "x" : 1, "y" : 1 }1
1
2> db.test.aggregate( [ { $project: { myArray: [ "$x", "$y" ] } } ] ) { "_id" : ObjectId("55ad167f320c6be244eb3b95"), "myArray" : [ 1, 1 ] }12
1
2>db.test.aggregate( [ { $project: { myArray: [ "$x", "$y", "$someField" ] } } ] ) { "_id" : ObjectId("55ad167f320c6be244eb3b95"), "myArray" : [ 1, 1, null ] }12
$limit
1{ $limit: <positive integer> }1
1
2
3db.article.aggregate( { $limit : 5 } );
$skip
1{ $skip: <
1positive integer> }示例:
1
2
3db.article.aggregate( { $skip : 5 } );
$sort
1{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
1指定升序。
-1指定降序。
{$meta:“textScore”}按照降序排列计算出的textScore元数据。
1
2
3
4
5db.users.aggregate( [ { $sort : { age : -1, posts: 1 } } ] )
1
2
3
4
5
6
7
8
9
10
11
12
13MinKey (internal type) Null Numbers (ints, longs, doubles, decimals) Symbol, String Object Array BinData ObjectId Boolean Date Timestamp Regular Expression MaxKey (internal type)
$sortByCount
1{ $sortByCount: <expression> }
最后
以上就是开朗过客最近收集整理的关于mongodb高级聚合查询的全部内容,更多相关mongodb高级聚合查询内容请搜索靠谱客的其他文章。
发表评论 取消回复