From 1cb3de7dd0e275cf50b8d62a7bacbb9d01516bf9 Mon Sep 17 00:00:00 2001 From: Melanie Ballard Date: Tue, 10 Jun 2025 16:05:54 -0400 Subject: [PATCH 1/3] DOCSP-50497 redo file deletion and new pull req with correct c# reference --- source/aggregation.txt | 329 +++++++++---------------- source/aggregation/pipeline-stages.txt | 239 ++++++++++++++++++ 2 files changed, 361 insertions(+), 207 deletions(-) create mode 100644 source/aggregation/pipeline-stages.txt diff --git a/source/aggregation.txt b/source/aggregation.txt index c4f2504e4..874ab0ddc 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -14,245 +14,160 @@ Aggregation .. contents:: On this page :local: + :backlinks: none :depth: 2 :class: singlecol .. toctree:: + Pipeline Stages Filtered Subset Group & Total Unpack Arrays & Group One-to-One Join Multi-Field Join - + .. _nodejs-aggregation-overview: Overview -------- -In this guide, you can learn how to use **aggregation operations** in -the MongoDB Node.js driver. +In this guide, you can learn how to use the MongoDB Node.js Driver to perform +**aggregation operations**. -Aggregation operations are expressions you can use to produce reduced -and summarized results in 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. +Aggregation operations process data in your MongoDB collections and return +computed results. The MongoDB Aggregation framework is modeled on the +concept of data processing pipelines. Documents enter a pipeline comprised of one or +more stages, and this pipeline transforms the documents into an aggregated result. + +To learn more about the aggregation stages supported by the Node.js Driver, see :ref:`Aggregation Stages <>`. +.. todo-- add link here Analogy ~~~~~~~ -You can think of the aggregation pipeline 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 **expression operators** are the -specialized tools. - -Comparing Aggregation and Query Operations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Using query operations, such as the ``find()`` method, you can perform the following actions: - -- 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 :manual:`limitations `: - -- Returned documents must not violate the :manual:`BSON-document size limit ` +The aggregation pipeline is similar to an automobile factory assembly line. An +assembly lines has stations with specialized tools that are used to perform +specific tasks. For example, when building a car, the assembly line begins with +a frame. As the car frame moves though the assembly line, each station adds a +new part. The factory transforms and assembles the initial parts, resulting in +finished cars. + +The *aggregation pipeline* is the assembly line, the *aggregation stages* are +the assembly stations, and the *expression operators* are the specialized tools. + +Compare Aggregation and Find Operations +--------------------------------------- + +The following table lists the different tasks you can perform with find +operations compared to what you can achieve with aggregation +operations. The aggregation framework provides expanded functionality +that allows you to transform and manipulate your data. + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Find Operations + - Aggregation Operations + + * - | Select *certain* documents to return + | Select *which* fields to return + | Sort the results + | Limit the results + | Count the results + - | Select *certain* documents to return + | Select *which* fields to return + | Sort the results + | Limit the results + | Count the results + | Group the results + | Rename fields + | Compute new fields + | Summarize data + | Connect and merge data sets + +Server Limitations +------------------ + +Consider the following :manual:`limitations ` when performing aggregation operations: + +- Returned documents must not violate the :manual:`BSON document size limit ` of 16 megabytes. -- Pipeline stages have a memory limit of 100 megabytes by default. You can exceed this - limit by setting the ``allowDiskUse`` property of ``AggregateOptions`` to ``true``. See - the `AggregateOptions API documentation <{+api+}/interfaces/AggregateOptions.html>`__ - for more details. - -.. important:: $graphLookup exception - - The :manual:`$graphLookup - ` stage has a strict - memory limit of 100 megabytes and will ignore ``allowDiskUse``. - -References -~~~~~~~~~~ - -To view a full list of expression operators, see :manual:`Aggregation -Operators ` in the Server manual. - -To learn about assembling an aggregation pipeline and view examples, see -:manual:`Aggregation Pipeline ` in the -Server manual. - -To learn more about creating pipeline stages, see :manual:`Aggregation -Stages ` in the Server manual. - -Runnable Examples ------------------ - -The example uses sample data about restaurants. The following code -inserts data into the ``restaurants`` collection of the ``aggregation`` -database: - -.. literalinclude:: /code-snippets/aggregation/agg.js - :start-after: begin data insertion - :end-before: end data insertion - :language: javascript - :dedent: - -.. tip:: - - For more information on connecting to your MongoDB deployment, see the :doc:`Connection Guide `. +- Pipeline stages have a memory limit of 100 megabytes by default. If required, + you can exceed this limit by enabling the `AllowDiskUse + `__ + property of the ``AggregateOptions`` object that you pass to the + ``Aggregate()`` method. +.. Aggregation Example -~~~~~~~~~~~~~~~~~~~ - +------------------- +.. To perform an aggregation, pass a list of aggregation stages to the ``collection.aggregate()`` method. - -In the example, the aggregation pipeline uses the following aggregation stages: - -- A :manual:`$match ` stage to filter for documents whose - ``categories`` array field contains the element ``Bakery``. - -- A :manual:`$group ` stage to group the matching documents by the ``stars`` - field, accumulating a count of documents for each distinct value of ``stars``. - +.. +.. note:: + .. + This example uses the ``sample_restaurants.restaurants`` collection + from the :atlas:`Atlas sample datasets `. To learn how to create a + free MongoDB Atlas cluster and load the sample datasets, see the :ref:`Get Started ` guide. +.. +The following code example produces a count of the number of bakeries in each borough +of New York City. To do so, the aggregation pipeline uses the following aggregation stages: +.. +- A :manual:`$match ` stage to filter + for documents whose ``cuisine`` field contains the element ``Bakery``. +.. +- A :manual:`$group ` stage to group the + matching documents by the ``borough`` field, accumulating a count of documents + for each distinct value in the ``borough`` field. +.. .. literalinclude:: /code-snippets/aggregation/agg.js :start-after: begin aggregation :end-before: end aggregation :language: javascript :dedent: - +.. This example produces the following output: - +.. .. code-block:: json :copyable: false - - { _id: 4, count: 2 } - { _id: 3, count: 1 } - { _id: 5, count: 1 } - -For more information, see the `aggregate() API documentation <{+api+}/classes/Collection.html#aggregate>`__. - -.. _node-aggregation-tutorials-landing: -.. _node-aggregation-tutorials: - -Aggregation Tutorials ---------------------- - -Aggregation tutorials provide detailed explanations of common -aggregation tasks in a step-by-step format. The tutorials are adapted -from examples in the `Practical MongoDB Aggregations book -`__ by Paul Done. - -Each tutorial includes the following sections: - -- **Introduction**, which describes the purpose and common use cases of the - aggregation type. This section also describes the example and desired - outcome that the tutorial demonstrates. - -- **Before You Get Started**, which describes the necessary databases, - collections, and sample data that you must have before building the - aggregation pipeline and performing the aggregation. - -- **Tutorial**, which describes how to build and run the aggregation - pipeline. This section describes each stage of the completed - aggregation tutorial, and then explains how to run and interpret the - output of the aggregation. - -At the end of each aggregation tutorial, you can find a link to a fully -runnable Node.js code file that you can run in your environment. - -.. tip:: - - To learn more about performing aggregations, see the - :ref:`node-aggregation` guide. - -.. _node-agg-tutorial-template-app: - -Aggregation Template App -~~~~~~~~~~~~~~~~~~~~~~~~ - -Before you begin following an aggregation tutorial, you must set up a -new Node.js app. You can use this app to connect to a MongoDB -deployment, insert sample data into MongoDB, and run the aggregation -pipeline in each tutorial. - -.. tip:: - - To learn how to install the driver and connect to MongoDB, - see the :ref:`node-get-started-download-and-install` and - :ref:`node-get-started-create-deployment` steps of the - Quick Start guide. - -Once you install the driver, create a file called -``agg_tutorial.js``. Paste the following code in this file to create an -app template for the aggregation tutorials: - -.. literalinclude:: /includes/aggregation/template-app.js - :language: javascript - :copyable: true - -.. important:: - - In the preceding code, read the code comments to find the sections of - the code that you must modify for the tutorial you are following. - - If you attempt to run the code without making any changes, you will - encounter a connection error. - -For every tutorial, you must replace the connection string placeholder with -your deployment's connection string. - -.. tip:: - - To learn how to locate your deployment's connection string, see the - :ref:`node-get-started-connection-string` step of the Quick Start guide. - -For example, if your connection string is -``"mongodb+srv://mongodb-example:27017"``, your connection string assignment resembles -the following: - -.. code-block:: javascript - :copyable: false - - const uri = "mongodb+srv://mongodb-example:27017"; - -To run the completed file after you modify the template for a -tutorial, run the following command in your shell: - -.. code-block:: bash - - node agg_tutorial.js - -Available Tutorials -~~~~~~~~~~~~~~~~~~~ - -- :ref:`node-aggregation-filtered-subset` -- :ref:`node-aggregation-group-total` -- :ref:`node-aggregation-arrays` -- :ref:`node-aggregation-one-to-one` -- :ref:`node-aggregation-multi-field` - -Additional Examples -~~~~~~~~~~~~~~~~~~~ - -To view step-by-step explanations of common aggregation tasks, see the -:ref:`node-aggregation-tutorials-landing`. - -You can find another aggregation pipeline example in the `Aggregation -Framework with Node.js Tutorial -`_ -blog post on the MongoDB website. +.. + { _id = 'Bronx', count = 71 } + { _id = 'Brooklyn', count = 173 } + { _id = 'Staten Island', count = 20 } + { _id = 'Missing', count = 2 } + { _id = 'Manhattan', count = 221 } + { _id = 'Queens', count = 204 } + +Additional information +---------------------- + +To view a full list of expression operators, see +:manual:`Aggregation Operators `. + +.. +To learn more about assembling an aggregation pipeline and view examples, see +:manual:`Aggregation Pipeline `. +.. +To learn more about creating pipeline stages and view examples, see +:manual:`Aggregation Stages `. + +To learn about explaining MongoDB aggregation operations, see +:manual:`Explain Results ` and +:manual:`Query Plans `. + +.. +API Documentation +~~~~~~~~~~~~~~~~~ +.. +For more information about the aggregation operations discussed in this guide, see the +following API documentation: +.. +- `Collection() `__ +- `aggregate() `__ +- `AggregateOptions `__ +.. try to find $match and $group api links .. \ No newline at end of file diff --git a/source/aggregation/pipeline-stages.txt b/source/aggregation/pipeline-stages.txt new file mode 100644 index 000000000..8bebad2f2 --- /dev/null +++ b/source/aggregation/pipeline-stages.txt @@ -0,0 +1,239 @@ +.. _node-aggregation-pipeline-stages: + +=============== +Aggregation Pipeline Stages +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: node.js, code example, transform, pipeline + :description: Learn the different possible stages of the aggregation pipeline in the {+driver-short+}. + +Overview +------------ + +On this page, you can learn how to create an aggregation pipeline and pipeline +stages by using methods in the Node.js Driver. + +Build an Aggregation Pipeline +----------------------------- + +You can use the {+driver-short+} to build an aggregation pipeline by INSERT +HERE. See the following sections to learn more about each of these approaches. + +.. to do these sections + +Aggregation Stage Methods +------------------------- + +The following table lists the stages in the aggregation pipeline. The methods +retain the same name when used in Node.js. To learn more about an aggregation +stage and see a code example in a Node.js application, follow the link from the +stage name to its reference page in the {+mdb-server+} manual. + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Aggregation Stage + - Description + + * - :manual:`$bucket ` + - Categorizes incoming documents into groups, called buckets, + based on a specified expression and bucket boundaries. + + * - :manual:`$bucketAuto ` + - Categorizes incoming documents into a specific number of + groups, called buckets, based on a specified expression. + Bucket boundaries are automatically determined in an attempt + to evenly distribute the documents into the specified number + of buckets. + + * - :manual:`$changeStream ` + - Returns a change stream cursor for the + collection. This stage can occur only once in an aggregation + pipeline and it must occur as the first stage. + + * - :manual:`$changeStreamSplitLargeEvent ` + - Splits large change stream events that exceed 16 MB into smaller fragments returned + in a change stream cursor. + + You can use ``$changeStreamSplitLargeEvent`` only in a ``$changeStream`` pipeline, and + it must be the final stage in the pipeline. + + * - :manual:`$count ` + - Returns a count of the number of documents at this stage of + the aggregation pipeline. + + * - :manual:`$densify ` + - Creates new documents in a sequence of documents where certain values in a field are missing. + + * - :manual:`$documents ` + - Returns literal documents from input expressions. + + * - :manual:`$facet ` + - Processes multiple aggregation pipelines + within a single stage on the same set + of input documents. Enables the creation of multi-faceted + aggregations capable of characterizing data across multiple + dimensions, or facets, in a single stage. + + * - :manual:`$geoNear ` + - Returns documents in order of nearest to farthest from a + specified point. This method adds a field to output documents + that contains the distance from the specified point. + + * - :manual:`$graphLookup ` + - Performs a recursive search on a collection. This method adds + a new array field to each output document that contains the traversal + results of the recursive search for that document. + + * - :manual:`$group ` + - Groups input documents by a specified identifier expression + and applies the accumulator expressions, if specified, to + each group. Consumes all input documents and outputs one + document per each distinct group. The output documents + contain only the identifier field and, if specified, accumulated + fields. + + * - :manual:`$limit ` + - Passes the first *n* documents unmodified to the pipeline, + where *n* is the specified limit. For each input document, + outputs either one document (for the first *n* documents) or + zero documents (after the first *n* documents). + + * - :manual:`$lookup ` + - Performs a left outer join to another collection in the + *same* database to filter in documents from the "joined" + collection for processing. + + * - :manual:`$match ` + - Filters the document stream to allow only matching documents + to pass unmodified into the next pipeline stage. + For each input document, outputs either one document (a match) or zero + documents (no match). + + * - :manual:`$merge ` + - Writes the resulting documents of the aggregation pipeline to + a collection. The stage can incorporate (insert new + documents, merge documents, replace documents, keep existing + documents, fail the operation, process documents with a + custom update pipeline) the results into an output + collection. To use this stage, it must be + the last stage in the pipeline. + + * - :manual:`$out ` + - Writes the resulting documents of the aggregation pipeline to + a collection. To use this stage, it must be + the last stage in the pipeline. + + * - :manual:`$project ` + - Reshapes each document in the stream, such as by adding new + fields or removing existing fields. For each input document, + outputs one document. + + * - :manual:`$rankFusion ` + - Uses a rank fusion algorithm to combine results from a Vector Search + query and an Atlas Search query. + + * - :manual:`$replaceRoot ` + - Replaces a document with the specified embedded document. The + operation replaces all existing fields in the input document, + including the ``_id`` field. Specify a document embedded in + the input document to promote the embedded document to the + top level. + + The ``$replaceWith`` stage is an alias for the ``$replaceRoot`` stage. + + * - :manual:`$replaceWith ` + - Replaces a document with the specified embedded document. + The operation replaces all existing fields in the input document, including + the ``_id`` field. Specify a document embedded in the input document to promote + the embedded document to the top level. + + The ``$replaceWith`` stage is an alias for the ``$replaceRoot`` stage. + + * - :manual:`$sample ` + - Randomly selects the specified number of documents from its + input. + + * - :manual:`$search ` + - Performs a full-text search of the field or fields in an + :atlas:`Atlas ` + collection. + + This stage is available only for MongoDB Atlas clusters, and is not + available for self-managed deployments. To learn more, see + :atlas:`Atlas Search Aggregation Pipeline Stages + ` in the Atlas documentation. + + * - :manual:`$searchMeta ` + - Returns different types of metadata result documents for the + :atlas:`Atlas Search ` query against an + :atlas:`Atlas ` + collection. + + This stage is available only for MongoDB Atlas clusters, + and is not available for self-managed deployments. To learn + more, see :atlas:`Atlas Search Aggregation Pipeline Stages + ` in the Atlas documentation. + + * - :manual:`$set ` + - Adds new fields to documents. Like the ``Project()`` method, + this method reshapes each + document in the stream by adding new fields to + output documents that contain both the existing fields + from the input documents and the newly added fields. + + * - :manual:`$setWindowFields ` + - Groups documents into windows and applies one or more + operators to the documents in each window. + + * - :manual:`$skip ` + - Skips the first *n* documents, where *n* is the specified skip + number, and passes the remaining documents unmodified to the + pipeline. For each input document, outputs either zero + documents (for the first *n* documents) or one document (if + after the first *n* documents). + + * - :manual:`$sort ` + - Reorders the document stream by a specified sort key. The documents remain unmodified. + For each input document, outputs one document. + + * - :manual:`$sortByCount ` + - Groups incoming documents based on the value of a specified + expression, then computes the count of documents in each + distinct group. + + * - :manual:`$unionWith ` + - Combines pipeline results from two collections into a single + result set. + + * - :manual:`$unwind ` + - Deconstructs an array field from the input documents to + output a document for *each* element. Each output document + replaces the array with an element value. For each input + document, outputs *n* Documents, where *n* is the number of + array elements. *n* can be zero for an empty array. + + * - :manual:`$vectorSearch ` + - Performs an :abbr:`ANN (Approximate Nearest Neighbor)` or + :abbr:`ENN (Exact Nearest Neighbor)` search on a + vector in the specified field of an + :atlas:`Atlas ` collection. + + This stage is available only for MongoDB Atlas clusters, and is not + available for self-managed deployments. To learn more, see + :ref:`Atlas Vector Search `. + + + From 2c34f85e8e987c113d9b2f5a43180b714f3e632d Mon Sep 17 00:00:00 2001 From: Melanie Ballard Date: Tue, 10 Jun 2025 16:21:27 -0400 Subject: [PATCH 2/3] DOCSP-50497 fixing pages, removing comments, and finishing outline --- source/aggregation.txt | 63 +------------------------- source/aggregation/pipeline-stages.txt | 51 +++++++++++++++++++-- 2 files changed, 49 insertions(+), 65 deletions(-) diff --git a/source/aggregation.txt b/source/aggregation.txt index 874ab0ddc..e9b3ccf51 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -41,8 +41,7 @@ computed results. The MongoDB Aggregation framework is modeled on the concept of data processing pipelines. Documents enter a pipeline comprised of one or more stages, and this pipeline transforms the documents into an aggregated result. -To learn more about the aggregation stages supported by the Node.js Driver, see :ref:`Aggregation Stages <>`. -.. todo-- add link here +To learn more about the aggregation stages supported by the Node.js Driver, see :ref:`Aggregation Stages `. Analogy ~~~~~~~ @@ -102,72 +101,12 @@ Consider the following :manual:`limitations property of the ``AggregateOptions`` object that you pass to the ``Aggregate()`` method. -.. -Aggregation Example -------------------- -.. -To perform an aggregation, pass a list of aggregation stages to the -``collection.aggregate()`` method. -.. -.. note:: - .. - This example uses the ``sample_restaurants.restaurants`` collection - from the :atlas:`Atlas sample datasets `. To learn how to create a - free MongoDB Atlas cluster and load the sample datasets, see the :ref:`Get Started ` guide. -.. -The following code example produces a count of the number of bakeries in each borough -of New York City. To do so, the aggregation pipeline uses the following aggregation stages: -.. -- A :manual:`$match ` stage to filter - for documents whose ``cuisine`` field contains the element ``Bakery``. -.. -- A :manual:`$group ` stage to group the - matching documents by the ``borough`` field, accumulating a count of documents - for each distinct value in the ``borough`` field. -.. -.. literalinclude:: /code-snippets/aggregation/agg.js - :start-after: begin aggregation - :end-before: end aggregation - :language: javascript - :dedent: -.. -This example produces the following output: -.. -.. code-block:: json - :copyable: false -.. - { _id = 'Bronx', count = 71 } - { _id = 'Brooklyn', count = 173 } - { _id = 'Staten Island', count = 20 } - { _id = 'Missing', count = 2 } - { _id = 'Manhattan', count = 221 } - { _id = 'Queens', count = 204 } - Additional information ---------------------- To view a full list of expression operators, see :manual:`Aggregation Operators `. -.. -To learn more about assembling an aggregation pipeline and view examples, see -:manual:`Aggregation Pipeline `. -.. -To learn more about creating pipeline stages and view examples, see -:manual:`Aggregation Stages `. - To learn about explaining MongoDB aggregation operations, see :manual:`Explain Results ` and :manual:`Query Plans `. - -.. -API Documentation -~~~~~~~~~~~~~~~~~ -.. -For more information about the aggregation operations discussed in this guide, see the -following API documentation: -.. -- `Collection() `__ -- `aggregate() `__ -- `AggregateOptions `__ -.. try to find $match and $group api links .. \ No newline at end of file diff --git a/source/aggregation/pipeline-stages.txt b/source/aggregation/pipeline-stages.txt index 8bebad2f2..0f7945f22 100644 --- a/source/aggregation/pipeline-stages.txt +++ b/source/aggregation/pipeline-stages.txt @@ -30,7 +30,39 @@ Build an Aggregation Pipeline You can use the {+driver-short+} to build an aggregation pipeline by INSERT HERE. See the following sections to learn more about each of these approaches. -.. to do these sections +.. note:: + .. + This example uses the ``sample_restaurants.restaurants`` collection + from the :atlas:`Atlas sample datasets `. To learn how to create a + free MongoDB Atlas cluster and load the sample datasets, see the :ref:`Get Started ` guide. + +The following code example produces a count of the number of bakeries in each borough +of New York City. To do so, the aggregation pipeline uses the following aggregation stages: + +- A :manual:`$match ` stage to filter + for documents whose ``cuisine`` field contains the element ``Bakery``. +- A :manual:`$group ` stage to group the + matching documents by the ``borough`` field, accumulating a count of documents + for each distinct value in the ``borough`` field. + +.. literalinclude:: /code-snippets/aggregation/agg.js + :start-after: begin aggregation + :end-before: end aggregation + :language: javascript + :dedent: + +This example produces the following output: + +.. code-block:: json + :copyable: false + + { _id = 'Bronx', count = 71 } + { _id = 'Brooklyn', count = 173 } + { _id = 'Staten Island', count = 20 } + { _id = 'Missing', count = 2 } + { _id = 'Manhattan', count = 221 } + { _id = 'Queens', count = 204 } + Aggregation Stage Methods ------------------------- @@ -42,9 +74,9 @@ stage name to its reference page in the {+mdb-server+} manual. .. list-table:: :header-rows: 1 - :widths: 50 50 + :widths: 20 80 - * - Aggregation Stage + * - Stage - Description * - :manual:`$bucket ` @@ -235,5 +267,18 @@ stage name to its reference page in the {+mdb-server+} manual. available for self-managed deployments. To learn more, see :ref:`Atlas Vector Search `. +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about assembling an aggregation pipeline, see :manual:`Aggregation +Pipeline ` in the MongoDB Server manual. + +To learn more about creating pipeline stages, see :manual:`Aggregation Stages +` in the MongoDB Server manual. +For more information about the methods and classes used on this page, see the +following API documentation: +- `Collection() `__ +- `aggregate() `__ +- `AggregateOptions `__ From 5275d65f38bd172a000568e57bdd9c4aed6d6e41 Mon Sep 17 00:00:00 2001 From: Melanie Ballard Date: Fri, 13 Jun 2025 13:42:54 -0400 Subject: [PATCH 3/3] DOCSP-50497 define framework with no concrete example, save for server pages --- source/aggregation/pipeline-stages.txt | 46 +++++++------------------ source/code-snippets/aggregation/agg.js | 17 ++------- 2 files changed, 15 insertions(+), 48 deletions(-) diff --git a/source/aggregation/pipeline-stages.txt b/source/aggregation/pipeline-stages.txt index 0f7945f22..495bb1800 100644 --- a/source/aggregation/pipeline-stages.txt +++ b/source/aggregation/pipeline-stages.txt @@ -22,53 +22,33 @@ Overview ------------ On this page, you can learn how to create an aggregation pipeline and pipeline -stages by using methods in the Node.js Driver. +stages by using methods in the {+driver-short+}. Build an Aggregation Pipeline ----------------------------- -You can use the {+driver-short+} to build an aggregation pipeline by INSERT -HERE. See the following sections to learn more about each of these approaches. +You can use the {+driver-short+} to build an aggregation pipeline by adding +aggregation stages and operations to the aggregation framework. See the +following code to learn how to format the framework. -.. note:: - .. - This example uses the ``sample_restaurants.restaurants`` collection - from the :atlas:`Atlas sample datasets `. To learn how to create a - free MongoDB Atlas cluster and load the sample datasets, see the :ref:`Get Started ` guide. -The following code example produces a count of the number of bakeries in each borough -of New York City. To do so, the aggregation pipeline uses the following aggregation stages: +.. code-block:: javascript -- A :manual:`$match ` stage to filter - for documents whose ``cuisine`` field contains the element ``Bakery``. -- A :manual:`$group ` stage to group the - matching documents by the ``borough`` field, accumulating a count of documents - for each distinct value in the ``borough`` field. + // Defines the aggregation pipeline + const pipeline = [ + { $match: { ... } }, + { $group: { ... } } + ]; -.. literalinclude:: /code-snippets/aggregation/agg.js - :start-after: begin aggregation - :end-before: end aggregation - :language: javascript - :dedent: - -This example produces the following output: - -.. code-block:: json - :copyable: false - - { _id = 'Bronx', count = 71 } - { _id = 'Brooklyn', count = 173 } - { _id = 'Staten Island', count = 20 } - { _id = 'Missing', count = 2 } - { _id = 'Manhattan', count = 221 } - { _id = 'Queens', count = 204 } + // Executes the aggregation pipeline + const results = coll.aggregate(pipeline); Aggregation Stage Methods ------------------------- The following table lists the stages in the aggregation pipeline. The methods -retain the same name when used in Node.js. To learn more about an aggregation +are formatted as they are listed when used in Node.js. To learn more about an aggregation stage and see a code example in a Node.js application, follow the link from the stage name to its reference page in the {+mdb-server+} manual. diff --git a/source/code-snippets/aggregation/agg.js b/source/code-snippets/aggregation/agg.js index 62fff7cc3..baa68a079 100644 --- a/source/code-snippets/aggregation/agg.js +++ b/source/code-snippets/aggregation/agg.js @@ -10,24 +10,11 @@ async function run() { const db = client.db("aggregation"); const coll = db.collection("restaurants"); - // Create sample documents - 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" }, - ]; - - // Insert documents into the restaurants collection - const result = await coll.insertMany(docs); - // end data insertion - // begin aggregation // Define an aggregation pipeline with a match stage and a group stage const pipeline = [ - { $match: { categories: "Bakery" } }, - { $group: { _id: "$stars", count: { $sum: 1 } } } + { $match: { cuisine: "Bakery" } }, + { $group: { _id: "$borough", count: { $sum: 1 } } } ]; // Execute the aggregation