mongodb聚合管道用法
基本用法
db.collection.aggregate( [ { <stage> }, ... ] )
stage如下
| 名称 | 描述 |
| $addFields | 将新的字段添加到文档中,输出的文档包含已经存在的字段和新加入的字段 |
| $bucket | 根据指定的表达式和存储区边界将传入文档分组到称为buckets的组中。 |
| $bucketAuto | 根据指定的表达式将传入文档分类到特定数量的组(称为buckets)。存储区边界自动确定,试图将文档均匀分布到指定数量的buckets中。 |
| $collStats | 返回有关集合或视图的统计信息。 |
| $count | 返回聚合管道的计数 |
| $currentOp | 返回有关MongoDB部署的活动和/或休眠操作的信息 |
| $facet | 在同一组输入文档中的单个阶段内处理多个聚合流水线。支持创建多方面的聚合,能够在单个阶段中跨多个维度或方面表征数据。 |
| $geoNear | 根据地理空间点的接近度返回有序的文档流。包含地理空间数据的$ match,$ sort和$ limit功能。输出文件包含一个额外的距离字段,并可包含位置标识符字段。 |
| $graphLookup | 对集合执行递归搜索。为每个输出文档添加一个新的数组字段,其中包含该文档的递归搜索的遍历结果 |
| $group | 按指定的标识符表达式输入文档,并将累加器表达式(如果指定)应用于每个组。消耗所有输入文档并为每个不同的组输出一个文档。输出文件只包含标识符字段,如果指定了,则包含累积字段。 |
| $indexStats | 返回有关使用集合中每个索引的统计信息。 |
| $limit | 将未修改的前n个文档传递到管道,其中n是指定的限制。对于每个输入文档,输出一个文档(前n个文档)或零文档(前n个文档之后)。 |
| $listLocalSessions | 列出最近在当前连接的mongos或mongod实例中使用的所有活动会话。这些会话可能尚未传播到system.sessions集合。 |
| $listSessions | 列出所有活动时间足以传播到system.sessions集合的所有会话。 |
| $lookup | 将左外连接执行到同一数据库中的另一个集合,以过滤“已连接”集合中的文档进行处理。 |
| $match | 过滤文档流,只允许匹配的文档未经修改地传递到下一个管道阶段。 $ match使用标准的MongoDB查询。对于每个输入文档,输出一个文档(匹配)或零个文档(不匹配)。 |
| $out | 将聚合管道的结果文档写入集合。要使用$ out阶段,它必须是管道中的最后一个阶段。 |
| $project | 重新设计流中的每个文档,例如添加新字段或删除现有字段。对于每个输入文档,输出一个文档。 |
| $redact | 根据存储在文档本身中的信息限制每个文档的内容,重新整形流中的每个文档。包含$ project和$ match的功能。可用于实施字段级别的编校。对于每个输入文档,输出一个或零个文档。 |
| $replaceRoot | 用指定的嵌入式文档替换文档。该操作将替换输入文档中的所有现有字段,包括_id字段。指定嵌入在输入文档中的文档以将嵌入式文档提升到顶层。 |
| $sample | 从其输入中随机选择指定数量的文档。 |
| $skip | 跳过前n个文档,其中n是指定的跳过编号,并将未修改的其余文档传递到管道。对于每个输入文档,输出零文档(对于前n个文档)或一个文档(如果在前n个文档之后)。 |
| $sort | 通过指定的排序键对文档流进行重新排序。只有订单改变了;文件保持不变。对于每个输入文档,输出一个文档。 |
| $sortByCount | 根据指定表达式的值对传入文档分组,然后计算每个不同组中文档的数量。 |
| $unwind | 从输入文档解构数组字段以输出每个元素的文档。每个输出文档用一个元素值替换数组。对于每个输入文档,输出n个文档,其中n是数组元素的数量,对于空数组可以为零。 |
以上翻译自谷歌翻译
常用的stage有
$count
经常搭配其他的stage一起使用
样例
假设数据如下
{ "_id" : , "subject" : "History", "score" : }
{ "_id" : , "subject" : "History", "score" : }
{ "_id" : , "subject" : "History", "score" : }
{ "_id" : , "subject" : "History", "score" : }
{ "_id" : , "subject" : "History", "score" : }
{ "_id" : , "subject" : "History", "score" : }
使用以下聚合操作
db.scores.aggregate(
[
{
$match: {
score: {
$gt:
}
}
},
{
$count: "passing_scores"
}
]
)
意思是匹配score字段大于80分的文档,然后计算数量,重命名为passing_scores输出
输出如下
{ "passing_scores" : }
$group
用法如下
{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
<accumulator>操作如下
$sum,$avg,$first,$last,$max,$min,$push,$addToSet,$stdDevPop,$stdDevSamp
用途就跟名称差不多
样例
{ "_id" : , "item" : "abc", "price" : , "quantity" : , "date" : ISODate("2014-03-01T08:00:00Z") }
{ "_id" : , "item" : "jkl", "price" : , "quantity" : , "date" : ISODate("2014-03-01T09:00:00Z") }
{ "_id" : , "item" : "xyz", "price" : , "quantity" : , "date" : ISODate("2014-03-15T09:00:00Z") }
{ "_id" : , "item" : "xyz", "price" : , "quantity" : , "date" : ISODate("2014-04-04T11:21:39.736Z") }
{ "_id" : , "item" : "abc", "price" : , "quantity" : , "date" : ISODate("2014-04-04T21:23:13.331Z") }
使用以下聚合操作
db.sales.aggregate(
[
{
$group : {
_id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: }
}
}
]
)
意思是将文档根据时间(相同的年月日)分组,并计算其总价格(价格*数量求和),平均的数量,每个分组有多少个文档
结果如下
{ "_id" : { "month" : , "day" : , "year" : }, "totalPrice" : , "averageQuantity" : , "count" : }
{ "_id" : { "month" : , "day" : , "year" : }, "totalPrice" : , "averageQuantity" : , "count" : }
{ "_id" : { "month" : , "day" : , "year" : }, "totalPrice" : , "averageQuantity" : 1.5, "count" : }
使用以下聚合操作
db.sales.aggregate(
[
{
$group : {
_id : null,
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: }
}
}
]
)
结果如下
{ "_id" : null, "totalPrice" : , "averageQuantity" : 8.6, "count" : }
更多操作见https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
$limit
用法如下
db.article.aggregate(
{ $limit : }
);
意思就是现在article只返回前5个文档
$lookup
用法如下
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
from表示另一个要连接的表b,localField表示该表a中用于和表b连接的字段,foreignField表示表b中用于和表a连接的字段,as表示为输出结果命名
SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT *
FROM <collection to join>
WHERE <foreignField>= <collection.localField>);
相当于以上的sql语句
另一种用法
{
$lookup:
{
from: <collection to join>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to execute on the collection to join> ],
as: <output array field>
}
}
对应的sql语句
SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT <documents as determined from the pipeline>
FROM <collection to join>
WHERE <pipeline> );
样例
插入如下数据
db.orders.insert([
{ "_id" : , "item" : "almonds", "price" : , "quantity" : },
{ "_id" : , "item" : "pecans", "price" : , "quantity" : },
{ "_id" : }
])
db.inventory.insert([
{ "_id" : , "sku" : "almonds", description: "product 1", "instock" : },
{ "_id" : , "sku" : "bread", description: "product 2", "instock" : },
{ "_id" : , "sku" : "cashews", description: "product 3", "instock" : },
{ "_id" : , "sku" : "pecans", description: "product 4", "instock" : },
{ "_id" : , "sku": null, description: "Incomplete" },
{ "_id" : }
])
使用以下聚合操作
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
返回结果如下
{
"_id" : ,
"item" : "almonds",
"price" : ,
"quantity" : ,
"inventory_docs" : [
{ "_id" : , "sku" : "almonds", "description" : "product 1", "instock" : }
]
}
{
"_id" : ,
"item" : "pecans",
"price" : ,
"quantity" : ,
"inventory_docs" : [
{ "_id" : , "sku" : "pecans", "description" : "product 4", "instock" : }
]
}
{
"_id" : ,
"inventory_docs" : [
{ "_id" : , "sku" : null, "description" : "Incomplete" },
{ "_id" : }
]
}
相同sql语句如下
SELECT *, inventory_docs
FROM orders
WHERE inventory_docs IN (SELECT *
FROM inventory
WHERE sku= orders.item);
更多内容见https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup
$match
用法如下
{ $match: { <query> } }
样例
数据如下
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : , "views" : }
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : , "views" : }
{ "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : , "views" : }
{ "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : , "views" : }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : , "views" : }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b25a"), "author" : "li", "score" : , "views" : }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b25b"), "author" : "ty", "score" : , "views" : }
聚合操作如下
db.articles.aggregate(
[ { $match : { author : "dave" } } ]
);
结果如下
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : , "views" : }
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : , "views" : }
$out
用法如下
{ $out: "<output-collection>" }
样例
数据如下
{ "_id" : , "title" : "The Banquet", "author" : "Dante", "copies" : }
{ "_id" : , "title" : "Divine Comedy", "author" : "Dante", "copies" : }
{ "_id" : , "title" : "Eclogues", "author" : "Dante", "copies" : }
{ "_id" : , "title" : "The Odyssey", "author" : "Homer", "copies" : }
{ "_id" : , "title" : "Iliad", "author" : "Homer", "copies" : }
聚合操作如下
db.books.aggregate( [
{ $group : { _id : "$author", books: { $push: "$title" } } },
{ $out : "authors" }
] )
意思是将books的author字段分类并作为_id字段的内容,将相同作者的title都push到books字段中,将其插入authors表中
结果如下
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }
$project
用法如下
{ $project: { <specification(s)> } }
样例
数据如下
{
"_id" : ,
title: "abc123",
isbn: "",
author: { last: "zzz", first: "aaa" },
copies:
}
聚合操作如下
db.books.aggregate( [ { $project : { title : , author : } } ] )
结果如下
{ "_id" : , "title" : "abc123", "author" : { "last" : "zzz", "first" : "aaa" } }
更多内容见https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project
$skip
用法如下
{ $skip: <positive integer> }
样例
db.article.aggregate(
{ $skip : }
);
意思也很简单就是跳过前5个文档
$sort
用法如下
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
样例
db.users.aggregate(
[
{ $sort : { age : -, posts: } }
]
)
-1表示降序排列,1表示升序排列
$sortByCont
用法见https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/#pipe._S_sortByCount
$unwind
用法见https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind
mongodb聚合管道用法的更多相关文章
- MongoDB 聚合(管道与表达式)
MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). aggregate() 方法 MongoDB中 ...
- MongoDB基础教程系列--第七篇 MongoDB 聚合管道
在讲解聚合管道(Aggregation Pipeline)之前,我们先介绍一下 MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进行一系列操作,例如,求最 ...
- MongoDB聚合管道
通过上一篇文章中,认识了MongoDB中四个聚合操作,提供基本功能的count.distinct和group,还有可以提供强大功能的mapReduce. 在MongoDB的2.2版本以后,聚合框架中多 ...
- MongoDB 聚合管道
参见:http://www.cnblogs.com/liruihuan/p/6686570.html MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进 ...
- MongoDB 聚合管道(Aggregation Pipeline)
管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...
- MongoDB聚合管道(Aggregation Pipeline)
参考聚合管道简介 聚合管道 聚合管道是基于数据处理管道模型的数据聚合框架.文档进入一个拥有多阶段(multi-stage)的管道,并被管道转换成一个聚合结果.最基本的管道阶段提供了跟查询操作类似的过滤 ...
- MongoDB 聚合管道(aggregate)
1.aggregate() 方法 我们先插入一些测试数据 { "_id" : ObjectId("5abc960c684781cda6d38027"), &qu ...
- MongoDB 高级查询_aggregate聚合管道
MongoDB 聚合管道(AggregationPipeline) 使用聚合管道可以对集合中的文档进行变换和组合.实际项目应用主要是表关联查询.数据的统计. MongoDB 中使用 db.COLLEC ...
- 【翻译】MongoDB指南/聚合——聚合管道
[原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...
随机推荐
- loadrunner可用许可证
global-100: AEAMAUIK-YAFEKEKJJKEEA-BCJGIweb-10000: AEABEXFR-YTIEKEKJJMFKEKEKWBRAUNQJU-KBYGBglobal-10 ...
- bzoj 1108
思路:水题, 将所有点按x轴对称反转,就变成了两堆点的坐标和的差.. #include<bits/stdc++.h> #define LL long long #define fi fir ...
- 一个完整的 JS 身份证校验代码
一个完整的 JS 身份证校验代码 身份证号码是由 18 位数字组成的,它们分别表示: (1) 前 1.2 位数字表示: 所在省份的代码; (2) 第 3.4 位数字表示: 所在城市的代码; (3) 第 ...
- 修改MySQL事件
MySQL允许您更改现有事件的各种属性. 要更改现有事件,请使用ALTER EVENT语句,如下所示: ALTER EVENT event_name ON SCHEDULE schedule ON C ...
- Django Rest Framework(版本、解析器、序列化、数据验证)
一.版本 程序也来越大时,可能通过版本不同做不同的处理 没用rest_framework之前,我们可以通过以下这样的方式去获取. class UserView(APIView): def get(se ...
- lambda 表达式+python内置函数
#函数 def f1(a,b): retrun a+b #lambda方式,形参(a,b):返回值(a+b) f2=lambda a,b : a+b 在一些比较简单的过程计算就可以用lambda p ...
- 批量 修改 android eclipse 项目名
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 最外层的 文件夹名字.
- 「WC2018即时战略」
「WC2018即时战略」 题目描述 小 M 在玩一个即时战略 (Real Time Strategy) 游戏.不同于大多数同类游戏,这个游戏的地图是树形的.也就是说,地图可以用一个由 \(n\) 个结 ...
- 《pyhton学习手册》 第33章 异常编码细节
try/except/else语句 这些语句的一般的格式如下图所示 其中try中定义了主要执行的动作.except中定义了try语句当中发生异常的处理器.else定义了没有发生异常时候的处理器. tr ...
- 桥接模式:探索JDBC的接口
目录概要 场景问题 假设要设计一个电脑商场管理系统的某个模块设计,电脑分为品牌和类型两个纬度,我们应该怎么解决?我们初学者最容易想到的办法就是利用继承的方式,那利用继承实现的类图又是什么样子呢?我们看 ...