search
HomeDatabaseMysql TutorialMongodb中数据聚合之聚合管道aggregate

在之前的两篇文章 Mongodb中数据聚合之基本聚合函数count、distinct、group 和 Mongodb中数据聚合之MapReduce 中,我们已经对数据聚合提供了两种实现方式,今天,在这篇文章中,我们讲讲在Mongodb中的另外一种数据聚合实现方式——聚合管道aggregate。 面对

在之前的两篇文章Mongodb中数据聚合之基本聚合函数count、distinct、group >和Mongodb中数据聚合之MapReduce >中,我们已经对数据聚合提供了两种实现方式,今天,在这篇文章中,我们讲讲在Mongodb中的另外一种数据聚合实现方式——聚合管道aggregate。


面对着广大用户对数据统计的需求,Mongodb从2.2版本之后便引入了新的功能聚合框架(aggregation framework),它是数据聚合的新框架,这个概念类似于数据处理中的管道。每个文档通过一个由多个节点组成的管道,每个节点都有自己的特殊的作用(分组、过滤等),文档经过由多个节点组成的管道后最终得到输出结果。管道基本的功能有两种:(1)对文档进行过滤,筛选出符合条件的文档;(2)对文档进行变换,改变文档的输出结构。


聚合管道的使用方式:db.collection.aggregate();

对于管道中的多个节点可以使用以下几种管道操作符,下面对各种管道操作符的功能进行描述:

$project:修改文档的结构(重命名、增加或删除域),也可以用于创建计算结果以及嵌套文档。
$match:过滤数据,只输出符合条件的文档。
$limit:限制MongoDB聚合管道返回的文档数。
$skip:在聚合管道中跳过指定数量的文档。
$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
$group:将集合中的文档分组,可用于统计结果。
$sort:文档排序输出。
$geoNear:输出接近某一地理位置的有序文档。


举两个简单的例子:

db.article.aggregate(
    { $project : {
        title : 1 ,
        author : 1 ,
    }}
 );

db.articles.aggregate( [
                        { $match : { score : { $gt : 70, $lte : 90 } } },
                        { $group: { _id: user, count: { $sum: 1 } } }
                       ] );

下面对聚合管道使用过程中需要注意的地方进行说明:

(1)管道的是具有先后顺序的。
(2)$group操作目前是在内存中处理的,因此,不能对大量的文档进行使用该种方式进行分组操作;
(3)使用$unwind对数组中的字段值进行拆分时需要注意不能忘记写$符号,如{$unwind:"$tags"},tags字段前面有个$号;
(4)MongoDB 24.对内存做了优化,如果$sort出现在$limit之前,$sort只会对前$limit个文档进行操作,在内存中也只会保留前$limit个文档,节省了内存
(5)$sort操作是在内存中进行的,如果其占有的内存超过物理内存的10%,程序会产生错误

(6)管道的输出结果大小不能大于16M,超过会出现错误。
(7)如果一个管道操作符在执行过程中所占用的内存超过系统内存容量的10%,则会报错;
(8)聚合管道可以提供很好的性能和一致的接口,使用起来比较简单,对于一些简单的固定的聚集操作可以使用管道,但是对于一些复杂的、大量数据集的聚合任务还是使用MapReduce。

至此,关于Mongodb数据库内的数据聚合操作的简单描述便结束了,如果大家想更深入的学习了解,我觉得官网才是最好的教材,奋斗

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version