Aggregation聚合¶
On this page
Overview概述¶
In this guide, you can learn how to use aggregation operations in the MongoDB Node.js driver.在本指南中,您可以学习如何在MongoDB Node.js驱动程序中使用聚合操作。
Aggregation operations are expressions you can use to produce reduced and summarized results in MongoDB. 聚合操作是可用于在MongoDB中生成简化和汇总结果的表达式。MongoDB's aggregation framework allows you to create a pipeline that consists of one or more stages, each of which performs a specific operation on your data.MongoDB的聚合框架允许您创建一个由一个或多个阶段组成的管道,每个阶段对您的数据执行特定的操作。
You can think of the aggregation framework as similar to an automobile factory. 您可以将聚合框架视为类似于汽车工厂。Automobile manufacturing requires the use of assembly stations organized into assembly lines. 汽车制造需要使用装配站,装配站组织成装配线。Each station has specialized tools, such as drills and welders. 每个工位都有专用工具,如钻头和焊工。The factory transforms and assembles the initial parts and materials into finished products.工厂将最初的零件和材料转换和组装成成品。
The aggregation pipeline is the assembly line, aggregation stages are the assembly stations, and operator expressions are the specialized tools.聚合管道是装配线,聚合阶段是装配站,运算符表达式是专用工具。
Aggregation vs. Query Operations聚合与查询操作的对比¶
Using query operations, such as the 使用查询操作(如find()
method, you can perform the following actions:find()
方法),可以执行以下操作:
Select which documents to return.选择要返回的文档。Select which fields to return.选择要返回的字段。Sort the results.对结果进行排序。
Using aggregation operations, you can perform the following actions:使用聚合操作,可以执行以下操作:
Perform all query operations.执行所有查询操作。Rename fields.重命名字段。Calculate fields.计算字段。Summarize data.总结数据。Group values.组值。
Aggregation operations have some limitations:聚合操作有一些限制:
Returned documents must not violate the BSON-document size limit of 16 megabytes.返回的文档不得违反BSON文档大小限制(16 MB)。Pipeline stages have a memory limit of 100 megabytes by default.默认情况下,管道级的内存限制为100 MB。If necessary, you may exceed this limit by setting the如有必要,可以通过将allowDiskUse
property ofAggregateOptions
totrue
.AggregateOptions
的allowDiskUse
属性设置为true
来超过此限制。See the AggregateOptions API documentation for more details.有关更多详细信息,请参阅AggregateOptions API文档。
The $graphLookup stage has a strict memory limit of 100 megabytes and will ignore $graphLookup阶段有100兆字节的严格内存限制,将忽略allowDiskUse
.allowDiskUse
。
Useful References有用的参考资料¶
Runnable Examples可运行的示例¶
The example uses sample data about restaurants. 该示例使用有关餐厅的示例数据。The following code inserts data into the 以下代码将数据插入restaurants
collection of the aggregation
database:aggregation
数据库的restaurants
集合:
const db = client.db("aggregation");
const coll = db.collection("restaurants");
const docs = [
{ stars: 3, categories: ["Bakery", "Sandwiches"], name: "Rising Sun Bakery" },
{ stars: 4, categories: ["Bakery", "Cafe", "Bar"], name: "Cafe au Late" },
{ stars: 5, categories: ["Coffee", "Bakery"], name: "Liz's Coffee Bar" },
{ stars: 3, categories: ["Steak", "Seafood"], name: "Oak Steakhouse" },
{ stars: 4, categories: ["Bakery", "Dessert"], name: "Petit Cookie" },
];
const result = await coll.insertMany(docs);
For more information on connecting to your MongoDB deployment, see the Connection Guide.有关连接到MongoDB部署的更多信息,请参阅连接指南。
Aggregation Example聚合示例¶
To perform an aggregation, pass a list of aggregation stages to the 要执行聚合,请将聚合阶段的列表传递给collection.aggregate()
method.collection.aggregate()
方法。
In the example, the aggregation pipeline uses the following aggregation stages:在该示例中,聚合管道使用以下聚合阶段:
A $match stage to filter for documents whose$match阶段,用于筛选其categories
array field contains the elementBakery
.categories
数组字段包含元素Bakery的文档。A $group stage to group the matching documents by the$group阶段,用于按stars
field, accumulating a count of documents for each distinct value ofstars
.stars
字段对匹配的文档进行分组,为每个不同的stars
值累积文档计数。
const pipeline = [
{ $match: { categories: "Bakery" } },
{ $group: { _id: "$stars", count: { $sum: 1 } } }
];
const aggCursor = coll.aggregate(pipeline);
for await (const doc of aggCursor) {
console.log(doc);
}
This example should produce the following output:此示例应产生以下输出:
{ _id: 4, count: 2 }
{ _id: 3, count: 1 }
{ _id: 5, count: 1 }
For more information, see the aggregate() API documentation.有关更多信息,请参阅aggregate()
API文档。
Additional Aggregation Examples其他聚合示例¶
You can find another aggregation framework example in this MongoDB Blog post.您可以在这篇MongoDB博客文章中找到另一个聚合框架示例。