On this page本页内容
Aggregation operations process multiple documents and return computed results. 聚合操作处理多个文档并返回计算结果。You can use aggregation operations to:您可以使用聚合操作来:
To perform aggregation operations, you can use:要执行聚合操作,可以使用:
An aggregation pipeline consists of one or more stages that process documents:聚合管道由一个或多个处理文档的阶段组成:
Starting in MongoDB 4.2, you can also update documents with an aggregation pipeline. 从MongoDB 4.2开始,您还可以使用聚合管道更新文档。See Updates with Aggregation Pipeline.请参阅聚合管道的更新。
The following aggregation pipeline example contains two stages and returns the total order quantity of medium size pizzas grouped by pizza name:以下聚合管道示例包含两个阶段,并返回按披萨名称分组的中型披萨的总订单量:
db.orders.aggregate( [ // Stage 1: Filter pizza order documents by pizza size { $match: { size: "medium" } }, // Stage 2: Group remaining documents by pizza name and calculate total quantity { $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } } } ] )
size
of medium
.$group
stage.$group
阶段。name
.name
对其余文档进行分组。$sum
to calculate the total order quantity
for each pizza name
. $sum
计算每个披萨名称的总订购量。totalQuantity
field returned by the aggregation pipeline.totalQuantity
字段中。For runnable examples containing sample input documents, see Complete Aggregation Pipeline Examples.有关包含示例输入文档的可运行示例,请参阅完整的聚合管道示例。
You can use the following single purpose aggregation methods to aggregate documents from a single collection:可以使用以下单一用途聚合方法聚合单个集合中的文档:
db.collection.estimatedDocumentCount() | |
db.collection.count() | |
db.collection.distinct() |
The single purpose aggregation methods are simple but lack the capabilities of an aggregation pipeline.单一用途的聚合方法很简单,但缺乏聚合管道的功能。
Starting in MongoDB 5.0, map-reduce is deprecated:从MongoDB 5.0开始,不推荐使用map-reduce:
$group
, $merge
, and others.$group
、$merge
等)重写map-reduce操作。$accumulator
and $function
aggregation operators, available starting in version 4.4. $accumulator
和$function
聚合运算符,从版本4.4开始提供。For examples of aggregation pipeline alternatives to map-reduce, see:有关map reduce的聚合管道替代方案的示例,请参阅:
For a feature comparison of aggregation pipelines and map-reduce, see Aggregation Commands Comparison.有关聚合管道和map-reduce的功能比较,请参阅聚合命令比较。
To learn more about aggregations, see:要了解有关聚合的更多信息,请参阅: