mongodb聚合管道用法

时间:2022-09-02 20:58:55

基本用法

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聚合管道用法的更多相关文章

  1. MongoDB 聚合&lpar;管道与表达式&rpar;

    MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). aggregate() 方法 MongoDB中 ...

  2. MongoDB基础教程系列--第七篇 MongoDB 聚合管道

    在讲解聚合管道(Aggregation Pipeline)之前,我们先介绍一下 MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进行一系列操作,例如,求最 ...

  3. MongoDB聚合管道

    通过上一篇文章中,认识了MongoDB中四个聚合操作,提供基本功能的count.distinct和group,还有可以提供强大功能的mapReduce. 在MongoDB的2.2版本以后,聚合框架中多 ...

  4. MongoDB 聚合管道

     参见:http://www.cnblogs.com/liruihuan/p/6686570.html MongoDB 的聚合功能,聚合操作主要用于对数据的批量处理,往往将记录按条件分组以后,然后再进 ...

  5. MongoDB 聚合管道(Aggregation Pipeline)

    管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...

  6. MongoDB聚合管道(Aggregation Pipeline)

    参考聚合管道简介 聚合管道 聚合管道是基于数据处理管道模型的数据聚合框架.文档进入一个拥有多阶段(multi-stage)的管道,并被管道转换成一个聚合结果.最基本的管道阶段提供了跟查询操作类似的过滤 ...

  7. MongoDB 聚合管道(aggregate)

    1.aggregate() 方法 我们先插入一些测试数据 { "_id" : ObjectId("5abc960c684781cda6d38027"), &qu ...

  8. MongoDB 高级查询&lowbar;aggregate聚合管道

    MongoDB 聚合管道(AggregationPipeline) 使用聚合管道可以对集合中的文档进行变换和组合.实际项目应用主要是表关联查询.数据的统计. MongoDB 中使用 db.COLLEC ...

  9. 【翻译】MongoDB指南&sol;聚合——聚合管道

    [原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...

随机推荐

  1. thinkphp1

    命名空间 含义:从广义上来说,命名空间是一种封装事物的方法. 用途:用来解决命名冲突 namespace xxx\xxx; 使用: use xxx\xx\yy; new\xx\xx\yy; // 单一 ...

  2. IosPush推送通知的实现

    1. Apple推送通知的机制 上图可以分为三个阶段: 第一阶段:应用程序把要发送的消息.目的iPhone的标识打包,发给APNS. 第二阶段:APNS在自身的已注册Push服务的iPhone列表中, ...

  3. iOS&lowbar;UIImage&lowbar;裁切圆形头像

    github地址: https://github.com/mancongiOS/UIImage.git UIImage的Cagetory UIImage+ImageCircle.h - (UIImag ...

  4. 在Debian8&period;3中解决Odoo出现的问题:Unable to find Wkhtmltopdf on this system&period; The report will be shown in html&period;

    解决Odoo出现的问题:Unable to find Wkhtmltopdf on this system. The report will be shown in html. 下载wkhtmltop ...

  5. WPF学习随笔

    内容控件 Padding内边距,Margin外边距 1.ScrollViewer滚动条控件 <ScrollViewer VerticalScrollBarVisibility="Vis ...

  6. spring&plus;springmvc&plus;mybaties整合实例

    spring+springmvc+mybaties即SSM框架整合在ecpliseee中开发:很么多西都是只有只有自己上手做,才会懂.昨晚熬了很久,才弄出来.也希望对新手有帮助!下面整理一下思路:关键 ...

  7. Spring &commat;Component的作用详细介绍

    @component 作用 1.@controller 控制器(注入服务)2.@service 服务(注入dao)3.@repository dao(实现dao访问)4.@component (把普通 ...

  8. C&num;窗体-猜数字

    1.用到的控件:groupbox.label.textbox.button.menustrip等 2.实现的功能,随机产生一个数字,输入自己猜的答案,判断是否猜对. 3.运行结果 4.代码 using ...

  9. Unity shader学习之菲涅耳反射

    菲涅尔反射(Fresnel reflection),指光线照射物体表面时,一部分发生反射,一部分进入物体内部发生折射或散射,被反射的光和折射光之间存在一定的比率. 2个公式: 1. Schlick 菲 ...

  10. mingw 构建 mysql-connector-c-6&period;1&period;9记录

    1.准备工作 首先需要下载mysql-connector-c-6.1.9的源码,然后解压. 然后需要准备编译环境,这里我使用的是msys2(下载地址http://repo.msys2.org/dist ...