“Run Aggregation Pipelines” 通常指在 MongoDB 中执行聚合管道(Aggregation Pipeline)操作

张开发
2026/6/9 7:28:31 15 分钟阅读
“Run Aggregation Pipelines” 通常指在 MongoDB 中执行聚合管道(Aggregation Pipeline)操作
“Run Aggregation Pipelines” 通常指在 MongoDB 中执行聚合管道Aggregation Pipeline操作用于对集合中的文档进行一系列数据处理如筛选、分组、排序、投影、连接等最终返回转换后的结果。MongoDB 聚合管道由多个阶段stages组成每个阶段以$开头如$match,$group,$sort,$project,$lookup等按顺序执行前一阶段的输出作为后一阶段的输入。✅ 示例统计每个类别的商品数量并按数量降序排列db.products.aggregate([{$match:{status:active}},{$group:{_id:$category,count:{$sum:1}}},{$sort:{count:-1}}]) 注意事项聚合管道支持索引优化尤其$match和$sort放在前面更高效单次聚合默认内存限制为 100MB超限时需添加{ allowDiskUse: true }可在mongosh、MongoDB Compass、驱动程序如 PyMongo、Node.js MongoDB Driver中运行。PythonPyMongo示例frompymongoimportMongoClient clientMongoClient(mongodb://localhost:27017/)dbclient[mydb]pipeline[{$match:{price:{$gt:100}}},{$group:{_id:$brand,avgPrice:{$avg:$price}}}]resultlist(db.products.aggregate(pipeline,allowDiskUseTrue))print(result)Run Aggregation Pipelines¶MongoDB LogoServerDriversCloudToolsGuidesGet MongoDBClose ×MongoDB StitchIntroduction Tutorials Users Authentication MongoDB Atlas Overview Configure MongoDB Link a MongoDB Atlas Cluster Define Roles and Permissions Filter Incoming Queries Enforce a Document Schema Configure Advanced Rules Specify Cluster Read Preference Enable Wire Protocol Connections Work With MongoDB Add Data to MongoDB Find Documents in MongoDB Update Documents in MongoDB Delete Documents from MongoDB Watch for Document Changes Run Aggregation Pipelines Connect Over the Wire Protocol Reference MongoDB Actions Query Roles Query Filters Document Schemas Connection Strings Service Limitations CRUD Aggregation APIs GraphQL MongoDB Mobile Functions Triggers External Services Values Secrets Application Deployment Hosting Troubleshooting Stitch Administration Application Logs Client SDKs Release Notes Stitch MongoDB Atlas Work With MongoDBRun Aggregation PipelinesOn this pageOverview Data Model Snippet Setup Methods Aggregate Documents in a Collection Aggregation Stages Filter Documents Group Documents Project Document Fields Add Fields to Documents Unwind Array ValuesOverviewThe code snippets on this page demonstrate how configure and run aggregation pipelines against a collection. Aggregation operations run all documents in a collection through a series of data aggregation stages that allow you to filter and shape documents as well as collect summary data about groups of related documents.Supported Aggregation StagesStitch supports all MongoDB aggregation pipeline stages and operators, but some stages must be executed within a system function. See Aggregation Framework Limitations for more information.Data ModelThe examples on this page use a collection named store.purchases that contains information about historical item sales in an online store. Each document contains a list of the purchased items, including the item name and the purchased quantity, as well as a unique ID value for the customer that purchased the items.// store.purchases{_id: ,customerId: ,items: [ { name: , quantity: } ]}Snippet SetupFunctions JavaScript SDK Android SDK iOS SDKTo use a code snippet in a function, you must first instantiate a MongoDB collection handle:exports function() {const mongodb context.services.get(“mongodb-atlas”);const itemsCollection mongodb.db(“store”).collection(“items”);const purchasesCollection mongodb.db(“store”).collection(“purchases”);}MethodsAggregate Documents in a CollectionYou can execute an aggregation pipeline using the collection.aggregate() action.The following snippet groups all documents in the purchases collection by their customerId value and aggregates a count of the number of items each customer purchases as well as the total number of purchases that they made. After grouping the documents the pipeline adds a new field that calculates the average number of items each customer purchases at a time, averageNumItemsPurchased, to each customer’s document:Functions JavaScript SDK Android SDK iOS SDKconst pipeline [{ “KaTeX parse error: Expected }, got EOF at end of input: … _id: customerId”,“numPurchases”: { “KaTeX parse error: Expected EOF, got } at position 9: sum: 1 }̲, numIte…sum”: { “size:size: size:items” } }} },{ “KaTeX parse error: Expected }, got EOF at end of input: …d: { divide”: [“numItemsPurchased,numItemsPurchased, numItemsPurchased,numPurchases”]}} }]return purchasesCollection.aggregate(pipeline).toArray().then(customers {console.log(Successfully grouped purchases for ${customers.length} customers.)for(const customer of customers) {console.log(customer: ${_id})console.log(num purchases: ${customer.numPurchases})console.log(total items purchased: ${customer.numItemsPurchased})console.log(average items per purchase: ${customer.averageNumItemsPurchased})}return customers}).catch(err console.error(Failed to group purchases by customer: ${err}))Aggregation StagesFilter DocumentsYou can use the $match stage to filter incoming documents according to a standard query filter.{“$match”: {“”: ,…}}ExampleThe following $match stage filters incoming documents to include only those where the graduation_year field has a value between 2019 and 2024, inclusive.{“KaTeX parse error: Expected }, got EOF at end of input: …ear: { gte”: 2019,“$lte”: 2024},}}Group DocumentsYou can use the $group stage to aggregate summary data for groups of one or more documents. MongoDB groups documents based on the _id expression.NoteYou can reference a specific document field by prefixing the field name with a $.{“$group”: {“_id”: ,“”: ,…}}ExampleThe following $group stage groups documents by the value of their customerId field and calculates the number of purchase documents that each customerId appears in.{“KaTeX parse error: Expected }, got EOF at end of input: … { _id: customerId”,“numPurchases”: { “$sum”: 1 }}}Project Document FieldsYou can use the $project stage to include or omit specific fields from documents or to calculate new fields using aggregation operators. To include a field, set its value to 1. To omit a field, set its value to 0.NoteYou cannot simultaneously omit and include fields other than _id. If you explicitly include a field other than _id, any fields you did not explicitly include are automatically omitted (and vice-versa).{“$project”: {“”: 0 | 1 | Expression,…}}ExampleThe following $project stage omits the _id field, includes the customerId field, and creates a new field named numItems where the value is the number of documents in the items array:{“KaTeX parse error: Expected }, got EOF at end of input: …numItems: { sum”: { “size:size: size:items” } }}}Add Fields to DocumentsYou can use the $addFields stage to add new fields with calculated values using aggregation operators.Note$addFields is similar to $project but does not allow you to include or omit fields.ExampleThe following $addFields stages creates a new field named numItems where the value is the number of documents in the items array:{“KaTeX parse error: Expected }, got EOF at end of input: …numItems: { sum”: { “size:size: size:items” } }}}Unwind Array ValuesYou can use the $unwind stage to aggregate individual elements of array fields. When you unwind an array field, MongoDB copies each document once for each element of the array field but replaces the array value with the array element in each copy.{$unwind: {path: ,includeArrayIndex: ,preserveNullAndEmptyArrays:}}ExampleThe following $unwind stage creates a new document for each element of the items array in each document. It also adds a field called itemIndex to each new document that specifies the element’s position index in the original array:{“KaTeX parse error: Expected }, got EOF at end of input: …{ path: items”,“includeArrayIndex”: “itemIndex”}}Consider the following document from the purchases collection:{_id: 123,customerId: 24601,items: [{ name: “Baseball”, quantity: 5 },{ name: “Baseball Mitt”, quantity: 1 },{ name: “Baseball Bat”, quantity: 1 },]}If we apply the example $unwind stage to this document, the stage outputs the following three documents:{_id: 123,customerId: 24601,itemIndex: 0,items: { name: “Baseball”, quantity: 5 }}, {_id: 123,customerId: 24601,itemIndex: 1,items: { name: “Baseball Mitt”, quantity: 1 }}, {_id: 123,customerId: 24601,itemIndex: 2,items: { name: “Baseball Bat”, quantity: 1 }}← Watch for Document Changes Connect Over the Wire Protocol →

更多文章