On this page本页内容
aggregate
Performs aggregation operation using the aggregation pipeline. 使用聚合管道执行聚合操作。The pipeline allows users to process data from a collection or other source with a sequence of stage-based manipulations.管道允许用户通过一系列基于阶段的操作处理来自集合或其他源的数据。
Changed in version 5.0.在版本5.0中更改。
The command has following syntax:该命令具有以下语法:
{ aggregate: "<collection>" || 1, pipeline: [ <stage>, <...> ], explain: <boolean>, allowDiskUse: <boolean>, cursor: <document>, maxTimeMS: <int>, bypassDocumentValidation: <boolean>, readConcern: <document>, collation: <document>, hint: <string or document>, comment: <any>, writeConcern: <document>, let: <document> // Added in MongoDB 5.0 }
Rather than run the 大多数用户应该使用aggregate
command directly, most users should use the db.collection.aggregate()
helper provided in mongosh
or the equivalent helper in their driver.mongosh
中提供的db.collection.aggregate()
助手或驱动程序中的等效助手,而不是直接运行aggregate
命令。
The aggregate
command takes the following fields as arguments:aggregate
命令将以下字段作为参数:
aggregate | string | 1 for collection agnostic commands.1 表示与集合无关的命令。 |
pipeline | array | |
explain | boolean |
|
| boolean |
|
cursor | document |
aggregate command without the cursor option unless the command includes the explain option. cursor 选项的aggregate 命令,除非该命令包含explain 选项。explain option, you must specify the cursor option.explain 选项,否则必须指定cursor 选项。
|
maxTimeMS | non-negative integer |
|
bypassDocumentValidation | boolean |
|
readConcern | document |
|
collation | document |
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }
|
hint | string or document |
|
comment | any |
|
writeConcern | document |
|
let | document |
{ <variable_name_1>: <expression_1>, ..., <variable_name_n>: <expression_n> }
|
MongoDB 3.6 removes the use of MongoDB 3.6删除了不带aggregate
command without the cursor
option unless the command includes the explain
option. cursor
选项的aggregate
命令,除非该命令包含explain
选项。Unless you include the 除非包含explain
option, you must specify the cursor
option.explain
选项,否则必须指定cursor
选项。
cursor: {}
.cursor: {}
。cursor: {batchSize: <num> }
.cursor: {batchSize: <num> }
。For more information about the aggregation pipeline Aggregation Pipeline, Aggregation Reference, and Aggregation Pipeline Limits.有关聚合管道聚合管道、聚合引用和聚合管道限制的详细信息。
New in version 4.0.在版本4.0中新增。
For cursors created inside a session, you cannot call 对于在会话内创建的游标,不能在会话外调用getMore
outside the session.getMore
。
Similarly, for cursors created outside of a session, you cannot call 同样,对于在会话外部创建的游标,不能在会话内部调用getMore
inside a session.getMore
。
Starting in MongoDB 3.6, MongoDB drivers and 从MongoDB 3.6开始,MongoDB驱动程序和mongosh
associate all operations with a server session, with the exception of unacknowledged write operations. mongosh
将所有操作与服务器会话相关联,但未确认的写入操作除外。For operations not explicitly associated with a session (i.e. using 对于未显式与会话关联的操作(即使用Mongo.startSession()
), MongoDB drivers and mongosh
create an implicit session and associate it with the operation.Mongo.startSession()
),MongoDB驱动程序和mongosh
创建一个隐式会话并将其与操作关联。
If a session is idle for longer than 30 minutes, the MongoDB server marks that session as expired and may close it at any time. 如果会话空闲时间超过30分钟,MongoDB服务器会将该会话标记为已过期,并可随时将其关闭。When the MongoDB server closes the session, it also kills any in-progress operations and open cursors associated with the session. 当MongoDB服务器关闭会话时,它还会终止与会话相关联的任何正在进行的操作和打开的游标。This includes cursors configured with 这包括配置了noCursorTimeout()
or a maxTimeMS()
greater than 30 minutes.noCursorTimeout()
或大于30分钟的maxTimeMS()
的游标。
For operations that return a cursor, if the cursor may be idle for longer than 30 minutes, issue the operation within an explicit session using 对于返回游标的操作,如果游标空闲时间可能超过30分钟,请使用Mongo.startSession()
and periodically refresh the session using the refreshSessions
command. Mongo.startSession()
在显式会话中发出操作,并使用refreshSessions
命令定期刷新会话。See Session Idle Timeout for more information.有关详细信息,请参阅会话空闲超时。
aggregate
can be used inside multi-document transactions.可以在多文档事务中使用。
However, the following stages are not allowed within transactions:但是,以下阶段不允许在事务中进行:
You also cannot specify the 您也不能指定explain
option.explain
选项。
getMore
inside the transaction.getMore
。getMore
outside the transaction.getMore
。In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,并且多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化的数据模型(嵌入式文档和数组)将继续是您的数据和用例的最佳选择。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最小化多文档事务的需要。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
For 对于不包括aggregate
operation that do not include the $out
or $merge
stages:$out
或$merge
阶段的aggregate
操作:
Starting in MongoDB 4.2, if the client that issued the 从MongoDB 4.2开始,如果发出aggregate
disconnects before the operation completes, MongoDB marks the aggregate
for termination (i.e. killOp
on the operation).aggregate
的客户端在操作完成之前断开连接,MongoDB会将aggregate
标记为终止(即操作上的killOp
)。
When using Stable API V1:使用稳定API V1时:
You cannot use the following stages in an 不能在aggregate
command:aggregate
命令中使用以下阶段:
$collStats
stage, you can only use the count
field. $collStats
阶段时,只能使用count
字段。$collStats
fields are available.$collStats
字段可用。MongoDB 3.6 removes the use of MongoDB 3.6删除了不带aggregate
command without the cursor
option unless the command includes the explain
option. cursor
选项的aggregate
命令,除非该命令包含解释选项。Unless you include the 除非包含explain
option, you must specify the cursor option.explain
选项,否则必须指定游标选项。
cursor: {}
.cursor: {}
。cursor: {batchSize: <num> }
.cursor: {batchSize: <num> }
。Rather than run the 大多数用户应该使用aggregate
command directly, most users should use the db.collection.aggregate()
helper provided in mongosh
or the equivalent helper in their driver. mongosh
中提供的db.collection.aggregate()
助手或其驱动程序中的等效助手,而不是直接运行aggregate
命令。In 2.6 and later, the 在2.6及更高版本中,db.collection.aggregate()
helper always returns a cursor.db.collection.aggregate()
助手总是返回一个游标。
Except for the first two examples which demonstrate the command syntax, the examples in this page use the 除了演示命令语法的前两个示例外,本页中的示例使用db.collection.aggregate()
helper.db.collection.aggregate()
帮助程序。
A collection 集合articles
contains documents such as the following:articles
包含以下文档:
{ _id: ObjectId("52769ea0f3dc6ead47c9a1b2"), author: "abc123", title: "zzz", tags: [ "programming", "database", "mongodb" ] }
The following example performs an 以下示例对aggregate
operation on the articles
collection to calculate the count of each distinct element in the tags
array that appears in the collection.articles
集合执行aggregate
操作,以计算出现在集合中的tags
数组中的每个不同元素的计数。
db.runCommand( { aggregate: "articles", pipeline: [ { $project: { tags: 1 } }, { $unwind: "$tags" }, { $group: { _id: "$tags", count: { $sum : 1 } } } ], cursor: { } } )
In 在mongosh
, this operation can use the db.collection.aggregate()
helper as in the following:mongosh
中,此操作可以使用db.collection.aggregate()
助手,如下所示:
db.articles.aggregate( [ { $project: { tags: 1 } }, { $unwind: "$tags" }, { $group: { _id: "$tags", count: { $sum : 1 } } } ] )
$currentOp
The following example runs a pipeline with two stages on the admin database. 以下示例在管理数据库上运行具有两个阶段的管道。The first stage runs the 第一阶段运行$currentOp
operation and the second stage filters the results of that operation.$currentOp
操作,第二阶段筛选该操作的结果。
db.adminCommand( { aggregate : 1, pipeline : [ { $currentOp : { allUsers : true, idleConnections : true } }, { $match : { shard : "shard01" } } ], cursor : { } } )
The aggregate
command does not specify a collection and instead takes the form {aggregate: 1}
. aggregate
命令不指定集合,而是采用{aggregate:1}
的形式。This is because the initial 这是因为初始$currentOp
stage does not draw input from a collection. $currentOp
阶段不从集合中提取输入。It produces its own data that the rest of the pipeline uses.它生成其他管道使用的自己的数据。
The new 添加了新的db.aggregate()
helper has been added to assist in running collectionless aggregations such as this. db.aggregate()
帮助程序,以帮助运行此类无集合聚合。The above aggregation could also be run like this example.上面的聚合也可以像这个示例一样运行。
The following aggregation operation sets the optional field 以下聚合操作将可选字段explain
to true
to return information about the aggregation operation.explain
设置为true
,以返回有关聚合操作的信息。
db.orders.aggregate([ { $match: { status: "A" } }, { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }, { $sort: { total: -1 } } ], { explain: true } )
db.collection.aggregate()
method方法
Each individual pipeline stage has a limit of 100 megabytes of RAM. 每个管道级的RAM限制为100 MB。By default, if a stage exceeds this limit, MongoDB produces an error. 默认情况下,如果阶段超过此限制,MongoDB将生成错误。To allow pipeline processing to take up more space, set the allowDiskUse option to 要允许管道处理占用更多空间,请将true
to enable writing data to temporary files, as in the following example:allowDiskUse
选项设置为true
,以允许将数据写入临时文件,如下例所示:
db.stocks.aggregate( [ { $sort : { cusip : 1, date: 1 } } ], { allowDiskUse: true } )
Starting in MongoDB 4.2, the profiler log messages and diagnostic log messages includes a 从MongoDB 4.2开始,如果任何聚合阶段由于内存限制将数据写入临时文件,探查器日志消息和诊断日志消息都包含usedDisk
indicator if any aggregation stage wrote data to temporary files due to memory restrictions.usedDisk
指示符。
To specify an initial batch size, specify the 要指定初始批次大小,请在batchSize
in the cursor
field, as in the following example:cursor
字段中指定batchSize
,如下例所示:
db.orders.aggregate( [ { $match: { status: "A" } }, { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }, { $sort: { total: -1 } }, { $limit: 2 } ], { cursor: { batchSize: 0 } } )
The {batchSize: 0 }
document specifies the size of the initialbatch size only. {batchSize:0}
文档仅指定初始批大小的大小。Specify subsequent batch sizes to OP_GET_MORE operations as with other MongoDB cursors. 与其他MongoDB游标一样,为OP_GET_MORE操作指定后续批次大小。A batchSize
of 0
means an empty first batch and is useful if you want to quickly get back a cursor or failure message, without doing significant server-side work.batchSize
为0
表示第一批为空,如果您想快速返回游标或失败消息,而不需要做大量的服务器端工作,那么它非常有用。
Collation排序规则 allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。
A collection 集合myColl
has the following documents:myColl
包含以下文档:
{ _id: 1, category: "café", status: "A" } { _id: 2, category: "cafe", status: "a" } { _id: 3, category: "cafE", status: "a" }
The following aggregation operation includes the Collation option:以下聚合操作包括排序规则选项:
db.myColl.aggregate( [ { $match: { status: "A" } }, { $group: { _id: "$category", count: { $sum: 1 } } } ], { collation: { locale: "fr", strength: 1 } } );
For descriptions on the collation fields, see Collation Document.有关排序字段的描述,请参阅排序文档。
Create a collection 使用以下文档创建集合foodColl
with the following documents:foodColl
:
db.foodColl.insertMany( [ { _id: 1, category: "cake", type: "chocolate", qty: 10 }, { _id: 2, category: "cake", type: "ice cream", qty: 25 }, { _id: 3, category: "pie", type: "boston cream", qty: 20 }, { _id: 4, category: "pie", type: "blueberry", qty: 15 } ] )
Create the following indexes:创建以下索引:
db.foodColl.createIndex( { qty: 1, type: 1 } ); db.foodColl.createIndex( { qty: 1, category: 1 } );
The following aggregation operation includes the 以下聚合操作包含用于强制使用指定索引的hint
option to force the usage of the specified index:hint
选项:
db.foodColl.aggregate( [ { $sort: { qty: 1 }}, { $match: { category: "cake", qty: 10 } }, { $sort: { type: -1 } } ], { hint: { qty: 1, category: 1 } } )
To override the default read concern level, use the 要覆盖默认的读取关注级别,请使用readConcern
option. readConcern
选项。The getMore
command uses the readConcern
level specified in the originating aggregate
command.getMore
命令使用原始aggregate
命令中指定的readConcern
级别。
You cannot use the 您不能将$out
or the $merge
stage in conjunction with read concern "linearizable"
. $out
或$merge
阶段与读取关注点"linearizable"
结合使用。That is, if you specify 也就是说,如果为"linearizable"
read concern for db.collection.aggregate()
, you cannot include either stages in the pipeline.db.collection.aggregate()
指定"linearizable"
读取关注点,则不能在管道中包含这两个阶段。
The following operation on a replica set specifies a read concern of 以下对副本集的操作将读取关注指定为"majority"
to read the most recent copy of the data confirmed as having been written to a majority of the nodes."majority"
,以读取确认已写入大多数节点的数据的最新副本。
"majority"
for an aggregation that includes an $out
stage.$out
阶段的聚合指定读取关注级别"majority"
。$out
stage to use "majority"
read concern for the aggregation.$out
阶段来使用聚合的"majority"
读取关注点。db.restaurants.aggregate( [ { $match: { rating: { $lt: 5 } } } ], { readConcern: { level: "majority" } } )
To ensure that a single thread can read its own writes, use 要确保单个线程可以读取自己的写入,请对副本集的主线程使用"majority"
read concern and "majority"
write concern against the primary of the replica set."majority"
读取关注点和"majority"
写入关注点。
let
let
中使用变量New in version 5.0.在版本5.0中新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令中其他位置访问的变量,请使用let
选项。
Create a collection 创建包含蛋糕口味销售的集合cakeSales
containing sales for cake flavors:cakeSales
:
db.cakeSales.insertMany( [ { _id: 1, flavor: "chocolate", salesTotal: 1580 }, { _id: 2, flavor: "strawberry", salesTotal: 4350 }, { _id: 3, flavor: "cherry", salesTotal: 2150 } ] )
The following example:以下示例:
salesTotal
greater than 3000, which is the cake with an _id
of 2salesTotal
大于3000的蛋糕,即_id
为2的蛋糕targetTotal
variable in let
, which is referenced in $gt
as $$targetTotal
let
中定义targetTotal
变量,该变量在$gt
中被引用为$$targetToll
db.runCommand( { aggregate: db.cakeSales.getName(), pipeline: [ { $match: { $expr: { $gt: [ "$salesTotal", "$$targetTotal" ] } } }, ], cursor: {}, let: { targetTotal: 3000 } } )