当前位置:网站首页>MongoDB聚合操作总结
MongoDB聚合操作总结
2022-07-04 20:57:00 【cui_yonghua】
1. 聚合操作的作用
MongoDB 中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。
有点类似 SQL 语句中的 count(*), sum(), avg()。
2. aggregate() 方法
MongoDB中聚合的方法使用aggregate()。
语法格式:db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
案例:计算每个作者所写的文章数,使用aggregate()计算结果如下
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : 1}}}])
# 类似SQL语句
select by_user, count(*) from mycol group by by_user;
在上面的例子中,通过字段 by_user 字段对数据进行分组,并计算 by_user 字段相同值的总和。
3. 常见的聚合表达式
1、$sum 计算总和。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : "$likes"}}}])
1、$avg 计算平均值
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$avg : "$likes"}}}])
1、$min 获取集合中所有文档对应值得最小值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$min : "$likes"}}}])
1、$max 获取集合中所有文档对应值得最大值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$max : "$likes"}}}])
1、$push 将值加入一个数组中,不会判断是否有重复的值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$push: "$url"}}}])
1、$addToSet 将值加入一个数组中,会判断是否有重复的值,若相同的值在数组中已经存在了,则不加入。
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$addToSet : "$url"}}}])
1、$first 根据资源文档的排序获取第一个文档数据。
db.mycol.aggregate([{
$group : {
_id : "$by_user", first_url : {
$first : "$url"}}}])
1、$last 根据资源文档的排序获取最后一个文档数据
db.mycol.aggregate([{
$group : {
_id : "$by_user", last_url : {
$last : "$url"}}}])
4. 管道的概念
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。
MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。
聚合管道示意图:
相当于Sql语句: Select cust_id,sum(amount)as total from orders where status= "A"
聚合框架中常用的几个操作:
$project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。$match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。$limit:用来限制MongoDB聚合管道返回的文档数。$skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。$group:将集合中的文档分组,可用于统计结果。$sort:将输入文档排序后输出。$geoNear:输出接近某一地理位置的有序文档。
案例1:$project
db.article.aggregate({
$project: {
title: 1, author: 1,}});
# 默认情况下_id字段是被包含的,如果要想不包含_id话可以这样
db.article.aggregate({
$project: {
_id : 0 ,title: 1 ,author: 1}});
案例2:$match案例, 获取分数大于70小于或等于90记录,然后将符合条件的记录送到下一阶段$group管道操作符进行处理。
db.articles.aggregate([{
$match : {
score : {
$gt : 70, $lte : 90 } } },{
$group: {
_id: null, count: {
$sum: 1 } } }]);
案例3:经过$skip管道操作符处理后,前五个文档被"过滤"掉。
db.article.aggregate({
$skip : 5 });
5. SQL和聚合对应关系
| SQL术语、函数、概念 | MongoDB聚合操作 |
|---|---|
| WHERE | $match |
| GROUP BY | $group |
| HAVING | $match |
| SELECT | $project |
| ORDER BY | $sort |
| LIMIT | $limit |
| SUM() | $sum |
| COUNT() | $sum |
| join | $lookup (3.2版本新增) |
边栏推荐
- Redis transaction
- __ init__ () missing 2 required positive arguments
- 更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
- QT—绘制其他问题
- Huawei ENSP simulator enables devices of multiple routers to access each other
- Huawei ENSP simulator configures DHCP for router
- Kubeadm初始化报错:[ERROR CRI]: container runtime is not running
- 解析互联网时代的创客教育技术
- Learning breakout 3 - about energy
- 每日一题-LeetCode1200-最小绝对差-数组-排序
猜你喜欢

Huawei ENSP simulator configures ACL access control list

历史最全混合专家(MOE)模型相关精选论文、系统、应用整理分享

Redis 排查大 key 的3种方法,优化必备

WGCNA分析基本教程总结

How to use concurrentlinkedqueue as a cache queue

Interpreting the development of various intelligent organizations in maker Education

CAD中能显示打印不显示

Operation of adding material schedule in SolidWorks drawing

Stealing others' vulnerability reports and selling them into sidelines, and the vulnerability reward platform gives rise to "insiders"

改善机器视觉系统的方法
随机推荐
超详细教程,一文入门Istio架构原理及实战应用
Monitor the shuttle return button
How much is the minimum stock account opening commission? Is it safe to open an account online
创客思维在高等教育中的启迪作用
类方法和类变量的使用
Le module minidom écrit et analyse XML
AcWing 2022 每日一题
QT—双缓冲绘图
How to use concurrentlinkedqueue as a cache queue
【C语言】符号的深度理解
redis管道
Redis pipeline
Jerry's ad series MIDI function description [chapter]
奋斗正当时,城链科技战略峰会广州站圆满召开
GTEST from ignorance to proficiency (4) how to write unit tests with GTEST
巅峰不止,继续奋斗!城链科技数字峰会于重庆隆重举行
[buuctf.reverse] 151_[FlareOn6]DnsChess
Huawei ENSP simulator layer 3 switch
How to implement Devops with automatic tools
TCP三次握手,四次挥手,你真的了解吗?