{"id":101454,"date":"2024-04-02T16:20:58","date_gmt":"2024-04-02T16:20:58","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=101454"},"modified":"2024-11-14T22:20:17","modified_gmt":"2024-11-14T22:20:17","slug":"building-mongodb-aggregations-in-mongodb-compass","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/nosql\/mongodb\/building-mongodb-aggregations-in-mongodb-compass\/","title":{"rendered":"Building MongoDB Aggregations in MongoDB Compass"},"content":{"rendered":"<p><strong>This article is part of Robert Sheldon's continuing series on Mongo DB. To see all of the items in the series, <a href=\"https:\/\/www.red-gate.com\/simple-talk\/collections\/robert-sheldon-ongoing-mongodb-primer\/\">click here<\/a>.<\/strong><\/p>\n\n<p>In the previous article in this series, I demonstrated how to build and run an <code>aggregate<\/code> statement in MongoDB Shell. An <code>aggregate<\/code> statement makes it possible to group and summarize a collection\u2019s document data, as well as transform the data and control its output.<\/p>\n<p>For the examples in that article, I used the version of MongoDB Shell that is embedded in MongoDB Compass. This article continues the discussion on <code>aggregate<\/code> statements, except that the focus is now on the graphical components built into the Compass interface.<\/p>\n<p>Through the interface, you can build and edit complex aggregation pipelines that pull data from a MongoDB collection. The interface includes a rich set of features for building each stage in the pipeline and for visualizing your progress as you refine your stage definitions.<\/p>\n<p>To use these features effectively, however, you should have a basic understanding of how an <code>aggregate<\/code> statement works and what it takes to create an aggregation pipeline. For this reason, I highly recommend that you read the previous article before starting in on this one, unless you\u2019re already familiar with creating aggregations. The examples I demonstrate in this article build on many of the concepts introduced in the previous article, so the better the understand those concepts, the more you\u2019ll get out of this article.<\/p>\n<p>Specifically, this article walks you through the process of using the Compass GUI to build an aggregation pipeline. The article assumes that you already have a basic understanding of pipeline concepts and how to define the individual stages. If you\u2019ve reviewed the previous article, you should have no problem following along with the examples in this article. My focus here is primarily on using the interface, rather than in explaining stage elements I\u2019ve already covered.<\/p>\n<p>Note: For the examples in this article, I used MongoDB Atlas and MongoDB Compass. The last section of the article\u2014\u201cAppendix: Preparing your MongoDB environment\u201d\u2014provides information about how to set up your environment and includes a link to a .json file that you\u2019ll need to download if you want to try out these examples for yourself.<\/p>\n<h2>Introducing aggregations in the MongoDB Compass GUI<\/h2>\n<p>So far in this series, most of actions we performed in MongoDB Compass were either on the <strong>Documents<\/strong> tab of the main window or in the embedded MongoDB Shell. For this article, we won\u2019t be using either environment. Instead, we\u2019ll be working on the <strong>Aggregations<\/strong> tab, which is also part of the main interface window.<\/p>\n<p>The <strong>Aggregations<\/strong> tab includes a number of features that help simplify the process of creating an aggregation pipeline and their various stages. On this tab, you can also view and copy the pipeline code, which you can then use in your <code>aggregate<\/code> statements, whether running them in MongoDB Shell or incorporating them into your applications.<\/p>\n<p>To access the tab, you must first open the target collection, in this case, <code>sales<\/code>. (See the Appendix if you haven\u2019t already set up the <code>sales<\/code> collection.) The collection automatically opens in the <strong>Documents<\/strong> tab, but you can easily access the <strong>Aggregations<\/strong> tab by clicking <strong>Aggregations<\/strong> near the top of the main window.<\/p>\n<p>On the <strong>Aggregations<\/strong> tab, you\u2019ll find a preview of the collection\u2019s documents. The documents are displayed in a row (horizontally), as shown in the following figure. Within the row, you can scroll either left or right to view all the preview documents.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2968\" height=\"1300\" class=\"wp-image-101455\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-1.png\" \/><\/p>\n<p>The <strong>Aggregation<\/strong> tab provides a user-friendly environment for defining the stages in your pipeline. Each stage (except for the first) uses the output from the previous stage as its input. The stage then processes the inputted documents and outputs a set of documents that have been transformed in some way. If the stage is the first one in the pipeline, its input is the collection itself.<\/p>\n<p>As I walk you through the process of building an aggregation pipeline, I\u2019ll explain the various features available on the <strong>Aggregations<\/strong> tab. For this article, we\u2019ll create a pipeline that includes the same stages that we covered in the previous article (<code>$match<\/code>, <code>$unwind<\/code>, <code>$group<\/code>, <code>$project<\/code>, and <code>$sort<\/code>). We\u2019ll define the stages a bit differently from what we did in the last article, but the fundamentals will be much the same.<\/p>\n<p>The pipeline we create in this article will limit the results to customers who are over 30 years old and have purchased products within physical stores, as opposed to shopping online or by phone. For these customers, the pipeline will group the data first by product and then by gender. It will also calculate the total number of each product sold, as well as the average price for those products.<\/p>\n<h2>Adding a <code><strong>$match<\/strong><\/code> stage to your aggregation pipeline<\/h2>\n<p>An aggregation pipeline starts with the documents in the opened collection. As noted above, these documents provide the input for the first stage. The stage filters or transforms those documents in some way and then outputs the processed documents to the pipeline so they can be used by the next stage.<\/p>\n<p>For our pipeline, we\u2019ll start with a <code>$match<\/code> stage. This is a good place to start because the <code>$match<\/code> stage filters out the documents we don\u2019t need, reducing both processing and memory overhead. To control which documents are filtered out, we must specify one or more conditions. Only the documents that meet those conditions are passed down the pipeline to the next stage.<\/p>\n<p>To add a <code>$match<\/code> stage, click the <strong>Add Stage<\/strong> button at the bottom of the <strong>Aggregations<\/strong> tab. This adds a row beneath the collection row, as shown in the following figure. The new row (outlined in red) serves as a workspace for defining your stage.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2558\" height=\"1334\" class=\"wp-image-101456\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-2.png\" \/><\/p>\n<p>Near the upper left corner of the new row, you\u2019ll find the <strong>Stage 1<\/strong> drop-down list. From this list, select the <strong>$match<\/strong> option. Compass will populate the text box beneath the drop-down list with a comment and placeholder code. You\u2019ll also see an error message stating that the stage value is invalid. That message will disappear as soon as you add valid code.<\/p>\n<p>The purpose of the stage is to filter out all documents except those whose <code>purchaseMethod<\/code> field has a value of <code>In<\/code> <code>store<\/code> and whose <code>customer.age<\/code> field has a value greater than <code>30<\/code>. In row\u2019s the text box, delete the existing text, copy the following code, and paste it into the text box:<\/p>\n<pre class=\"lang:none theme:none\">{\n  $and: [\n    {\n      purchaseMethod: \"In store\",\n    },\n    {\n      \"customer.age\": { $gt: 30 },\n    },\n  ],\n}<\/pre>\n<p>When you add valid code to your stage definition, Compass automatically displays up to 10 documents from the stage\u2019s output, as shown in the following figure. (You can change the number of displayed documents in the tab\u2019s settings.) If you examine these documents, you\u2019ll see that each one has a <code>purchaseMethod<\/code> value of <code>In<\/code> <code>store<\/code> and a <code>customer.age<\/code> value greater than <code>30<\/code>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2950\" height=\"1350\" class=\"wp-image-101457\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-3.png\" \/><\/p>\n<p>That\u2019s all you need to do to create the first stage. However, there are a couple other features on the <strong>Aggregations<\/strong> tab that I want to point out. The first is Text View Mode.<\/p>\n<p>When you first open the <strong>Aggregations<\/strong> tab, it is in Stages View Mode. However, you can switch to Text View Mode by clicking the <strong>TEXT<\/strong> button near the upper right corner, just above the collections row. In this mode, you can view the pipeline code as it would appear in an <code>aggregate<\/code> statement. Text View Mode also provides a preview of the documents from of the data output, only now they\u2019re listed vertically, as shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2010\" height=\"1502\" class=\"wp-image-101458\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-4.png\" \/><\/p>\n<p>Another feature worth noting is Focus Mode, which you can access from Stages View Mode. If you\u2019re in Text View Mode, you can get back to Stages View Mode by clicking the <strong>STAGES<\/strong> button near the upper right corner, to the left of the <strong>TEXT<\/strong> button. In Stages View Mode, you\u2019ll find a button for Focus Mode at the upper right corner of the stage row, as shown in the following figure. The Focus Mode button is outlined in red.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2322\" height=\"816\" class=\"wp-image-101459\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-5.png\" \/><\/p>\n<p>When you click the button, the Focus Mode window opens, where you can work more easily with the current stage (in this case, <code>$match<\/code>). You can edit the stage definition, as well as easily view the stage\u2019s input and output preview documents, as shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2918\" height=\"1734\" class=\"wp-image-101460\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-6.png\" \/><\/p>\n<p>In Focus Mode, all the input and output document fields are collapsed, but you can choose to expand the fields by clicking the <strong>Options<\/strong> down-arrow at the top of either panel and then selecting <strong>Expand all fields<\/strong>. You can also expand the fields individually.<\/p>\n<p>It\u2019s up to you how much you want to use Focus Mode, but it\u2019s well worth knowing about when building your aggregation pipelines, especially as your stage definitions become more complex.<\/p>\n<p>In Stages View Mode and Text View Mode, you can also run your pipeline code at any time to view the full result set. The results are based on the currently active stages defined in the pipeline. The ability to run your pipeline code at any time is a handy feature when you want to view more than just the preview documents.<\/p>\n<p>To run the pipeline code, click the <strong>Run<\/strong> button in the upper right corner of the <strong>Aggregations<\/strong> tab. MongoDB will process the pipeline and return the results to the Compass window, as shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1992\" height=\"1438\" class=\"wp-image-101461\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-7.png\" \/><\/p>\n<p>In this case, MongoDB returns 50 documents. The collection contains 100 documents, which means that the <code>$match<\/code> stage filters out 50 documents. (It\u2019s pure chance that the <code>$match<\/code> stage filters out exactly half the documents.)<\/p>\n<p>After viewing your results, you can return to Stages View Mode by clicking the <strong>Edit<\/strong> button near the upper left corner. You can then continue to work on the pipeline.<\/p>\n<p>I also wanted to point out that you can save your work at any time. In this way, you can continue where you left off whenever you need to take a break from working on your aggregation. To save the pipeline the first time, click the <strong>Save<\/strong> down-arrow near the upper left corner, and then click <strong>Save<\/strong>. When the <strong>Save<\/strong> <strong>Pipeline<\/strong> dialog box appears, type a name for your pipeline in the <strong>Name<\/strong> text box, and then click <strong>Save<\/strong>. You can access your saved pipeline at any time from the <strong>My<\/strong> <strong>Queries<\/strong> screen.<\/p>\n<p>You can also re-save your pipeline at any time. You need only click the <strong>Save<\/strong> drop-down list and then click <strong>Save<\/strong>. You should save your changes often to minimize the risk of losing your work<\/p>\n<h2>Adding an <code><strong>$unwind<\/strong><\/code> stage to your aggregation pipeline<\/h2>\n<p>Now that you\u2019ve created the first stage to your aggregation, adding the subsequent stages should be fairly straightforward. Not surprisingly, the key is to ensure that you properly define each stage, just like you saw when building an <code>aggregate<\/code> statement in MongoDB Shell.<\/p>\n<p>One of the main advantages of the <strong>Aggregations<\/strong> tab is its ability to display the output data for each stage as you\u2019re working on it, making it possible to immediately verify whether your stage definition is correct and returning the data you want. If it doesn\u2019t display output data, either you have not yet defined your stage or there is an error in your code.<\/p>\n<p>With this in mind, let\u2019s move onto the next stage, which is <code>$unwind<\/code>. The <code>$unwind<\/code> stage deconstructs a specified array and generates a document for each of the array\u2019s elements. This makes it easier to work with the individual data elements within the array, which is useful when grouping and aggregating data.<\/p>\n<p>The <code>sales<\/code> collection includes the <code>items<\/code> array. The array contains most of the values we need for grouping and aggregating the data, so this is the array we\u2019ll specifying when defining the <code>$unwind<\/code> stage.<\/p>\n<p>To add the <code>$unwind<\/code> stage, click the <strong>Add Stage<\/strong> button at the bottom of the <strong>Aggregations<\/strong> tab. Compass will add a stage row beneath the first stage row. From the<strong> Stage 2<\/strong> drop-down list in the new row, select the <strong>$unwind<\/strong> option. (Notice how Compass automatically numbers each stage.) Next, delete the existing code in the stage\u2019s text box and add the following code:<\/p>\n<pre class=\"lang:none theme:none\">\"$items\"<\/pre>\n<p>That\u2019s all there is to it. As with the first stage, Compass displays the output preview documents to the right of the text box, as shown in the following figure. When you examine the documents, you\u2019ll see that some of them have identical <code>_id<\/code> values. This is because they originated from the same input document.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2946\" height=\"1148\" class=\"wp-image-101462\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-8.png\" \/><\/p>\n<p>If you were to run the pipeline with the additional stage, it would now return 263 documents, as opposed to the 50 documents that were inputted into the stage. The number of outputted documents depends on the number of elements in each document\u2019s array.<\/p>\n<p>You might have noticed in the figure that the collection row and first stage row are both minimized. You can minimize rows in this way to make it easier to view the current stage and to quickly see which stages are currently defined. All you need to do is click the arrow in the row\u2019s upper left corner. If you want to expand a row, click the arrow again.<\/p>\n<p>Minimizing stages also makes it easier to move them around. For example, suppose I had defined my pipeline with the <code>$unwind<\/code> stage first, followed by the <code>$match<\/code> stage, as shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2958\" height=\"666\" class=\"wp-image-101463\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-9.png\" \/><\/p>\n<p>After defining the two stages, I might then decide it would be better to start with <code>$match<\/code> stage. To change the stage order, all I need to do is to drag the <code>$match<\/code> stage upward, to just above the <code>$unwind<\/code> stage. Compass will automatically renumber the stages and process them in their new order. Note, however, that when you start moving stages around, you could potentially break the pipeline because of dependencies that exist between stages, so be sure to proceed cautiously whenever you start moving stages.<\/p>\n<p>Another feature on the <strong>Aggregations<\/strong> tab that I wanted to point out is the ability to add a stage before any existing stage. All you need to do is click the plus icon above that stage. In addition, each stage includes an options button (the ellipses in the row\u2019s upper right corner), which opens a menu that lists several options. From this menu, you can add a stage before or after the current stage. You can also delete the existing stage, expand all the fields in the preview documents, or collapse all the fields in those documents.<\/p>\n<h2>Adding a <code><strong>$group<\/strong><\/code> stage to your aggregation pipeline<\/h2>\n<p>The <code>$match<\/code> and <code>$unwind<\/code> stages have helped us prepare our documents for grouping and aggregating them. Once we have the documents the way we want them, we can add a <code>$group<\/code> stage, which we\u2019ll be using to group the documents by both the <code>items.name<\/code> field and <code>customer.gender<\/code> field.<\/p>\n<p>To add the <code>$group<\/code> stage, click the <strong>Add Stage<\/strong> button. In the new stage row, select the <strong>$group<\/strong> option from the<strong> Stage 3<\/strong> drop-down list and delete the existing code in the row\u2019s text box. Next, copy the following code and paste it into the text box:<\/p>\n<pre class=\"lang:none theme:none\">{\n  _id: {\n    name: \"$items.name\",\n    gender: \"$customer.gender\",\n  },\n  totalPurchased: {\n    $sum: \"$items.quantity\",\n  },\n  avgPrice: {\n    $avg: \"$items.price\",\n  },\n}<\/pre>\n<p>The code instructs MongoDB to group the documents first by the <code>items.name<\/code> field and then by the <code>customer.gender<\/code> field. When specifying the field names, you must precede each one with a dollar sign because it is part of an expression. The <code>items.name<\/code> group will be returned as the <code>name<\/code> output field, and the <code>customer.gender<\/code> group will be returned as the <code>gender<\/code> output field. Both output fields are part of the <code>_id<\/code> field, which is outputted as an embedded document.<\/p>\n<p>The remaining two elements in the code define the two aggregations. The first one uses the <code>$sum<\/code> operator to add together the values in the <code>items.quantity<\/code> field and return that total to the <code>totalPurchased<\/code> output field. The second one uses the <code>$avg<\/code> operator to find the average price of each product group, based on the <code>items.price<\/code> value. This total is assigned to the <code>avgPrice<\/code> output field.<\/p>\n<p>As soon as you add this code to your stage\u2019s text box, you\u2019ll see the preview documents, as shown in the following figure. The pipeline now includes only the grouped and aggregated data. Notice that the <code>_id<\/code> field is an embedded document that contains the <code>name<\/code> and <code>gender<\/code> fields.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2940\" height=\"1072\" class=\"wp-image-101464\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-10.png\" \/><\/p>\n<p>You can run the pipeline to verify your changes. As before, click the <strong>Run<\/strong> button in the upper right corner. At this point, the pipeline should now include only 14 documents. The following figure shows part of the results.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2000\" height=\"1486\" class=\"wp-image-101465\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-11.png\" \/><\/p>\n<p>One other item worth noting is that the <strong>Aggregations<\/strong> tab displays a set of icons near the upper left corner, with one icon for each pipeline stage. The icons include all the currently enabled stages, listed in the order that they\u2019re specified in the pipeline. I say \u201ccurrently enabled stages\u201d because it\u2019s possible for stages to be disabled.<\/p>\n<p>Each stage row in the Stages View Mode includes a toggle in the upper left corner that lets you enable or disable that particular stage. The stages are enabled by default, but you can disable one or more of them as you\u2019re working on your pipeline. When you disable a stage, it is no longer included in the pipeline\u2019s processing, nor is it in the set of icons near the top.<\/p>\n<p>For example, you might want disable the <code>$match<\/code> stage so you can see the aggregated totals for the entire collection rather than only a subset of documents. Once you get the information you need, you can then re-enable the stage without having to do any special coding.<\/p>\n<h2>Adding a <code><strong>$project<\/strong><\/code> stage to your aggregation pipeline<\/h2>\n<p>After you\u2019ve grouped and aggregated your data, you might find it useful to modify the fields themselves. For this, you can use the <code>$project<\/code> stage, which lets you add fields, remove fields, change their names, or modify their values. For this example, we\u2019ll use the stage to change the <code>name<\/code> and <code>gender<\/code> fields to top-level fields, removing the <code>_id<\/code> field in the process. We\u2019ll also round the <code>avgPrice<\/code> values to two decimal places.<\/p>\n<p>To add the <code>$project<\/code> stage, click the <strong>Add Stage<\/strong> button. In the new row, select the <strong>$project<\/strong> option from the<strong> Stage 4<\/strong> drop-down list and delete the existing code in the text box. Next, copy the following code and paste it into the text box:<\/p>\n<pre class=\"lang:none theme:none\">{\n  _id: 0,\n  product: \"$_id.name\",\n  gender: \"$_id.gender\",\n  totalPurchased: 1,\n  avgPrice: {\n    $round: [\"$avgPrice\", 2],\n  },\n}<\/pre>\n<p>The stage definition includes the following five specifications:<\/p>\n<ul>\n<li>The first specification states that the <code>_id<\/code> field should be suppressed. This is done by assigning a value of <code>0<\/code> to the field. The <code>_id<\/code> field is included by default, so you must specifically suppress it if you don\u2019t want it there.<\/li>\n<li>The second specification creates a new field named <code>product<\/code> and assigns the original <code>_id.name<\/code> value to the new field.<\/li>\n<li>The third specification creates a new field named <code>gender<\/code> and assigns the original <code>_id.gender<\/code> value to the new field.<\/li>\n<li>The fourth specification indicates that the <code>totalPurchased<\/code> field should be included. If you don\u2019t specify its inclusion, MongoDB automatically excludes it from the output. This is true for all fields except the <code>_id<\/code> field.<\/li>\n<li>The last specification defines a field named <code>avgPrice<\/code>. The field\u2019s expression rounds the values of the input <code>avgPrice<\/code> field to two decimal places. In effect, you\u2019re replacing the original field with a new field with the same name.<\/li>\n<\/ul>\n<p>As you\u2019ve seen with the previous stages, when you add the code to the stage\u2019s text box, Compass automatically displays the preview documents, as shown in the following figure. The documents no longer include any embedded fields, and the average prices are more readable.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2954\" height=\"1244\" class=\"wp-image-101466\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-12.png\" \/><\/p>\n<p>That\u2019s all you need to do to define the <code>$project<\/code> stage. As before, you can run your pipeline up to this point, disable specific stages, or make other changes. Be sure to save your changes periodically so you don\u2019t lose any of your work.<\/p>\n<h2>Adding a <code><strong>$sort<\/strong><\/code> stage to your aggregation pipeline<\/h2>\n<p>The final stage we\u2019ll be adding to our pipeline is the <code>$sort<\/code> stage, which orders the documents based on the specified fields. You can sort the documents by one or more fields, and you can choose to sort each field in either ascending or descending order. In this case, we\u2019ll be sorting the documents in ascending order, first by the <code>gender<\/code> field and then the <code>product<\/code> field.<\/p>\n<p>To add the <code>$sort<\/code> stage, click the <strong>Add Stage<\/strong> button and select the <strong>$sort<\/strong> option from the<strong> Stage 5<\/strong> drop-down list. In the text box, delete the existing code, copy the following code, and paste it into the text box:<\/p>\n<pre class=\"lang:none theme:none\">{\n  gender: 1,\n  product: 1,\n}<\/pre>\n<p>The code assigns a value of <code>1<\/code> to both fields, indicating that they should both be sorted in ascending order. If we wanted to sort the values in descending order, we would have specified <code>-1<\/code>. The following figure shows the new stage, along with the preview documents.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"2964\" height=\"1288\" class=\"wp-image-101467\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-13.png\" \/><\/p>\n<p>Given that the <code>$sort<\/code> stage is the final one you\u2019ll be adding to your pipeline, this is a good time to run the pipeline code again to ensure that it gives you the results you want. The documents should now be sorted first by the <code>gender<\/code> field and then the <code>product<\/code> field, as shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1992\" height=\"1494\" class=\"wp-image-101468\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-14.png\" \/><\/p>\n<p>If everything looks good and you\u2019re satisfied with your pipeline, you can copy the full pipeline definition and use it in your <code>aggregate<\/code> statements. Compass makes it fairly easy to copy the code. First, click the <strong>Edit<\/strong> button to return to Stages View Mode (if you haven\u2019t already) and then click the <strong>EXPORT TO LANGUAGE<\/strong> button. This launches the <strong>Export Pipeline To Language<\/strong> dialog box, shown in the following figure.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1948\" height=\"1156\" class=\"wp-image-101469\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2024\/02\/word-image-101454-15.png\" \/><\/p>\n<p>In the dialog box, you can copy the pipeline code to your clipboard. The code is available for MongoDB Shell (in the left pane) as well as for specific programming languages (in the right pane), including Python, Java, Node, C#, Ruby, and several others. You also have the option to include the applicable <code>Import<\/code> statements with the programming code, as well as the driver syntax. (Both options are selected in the figure.)<\/p>\n<h2>Getting started with MongoDB aggregations in MongoDB Compass<\/h2>\n<p>In this article, I\u2019ve tried to cover most of the features available to the <strong>Aggregations<\/strong> tab in the Compass interface. I\u2019ve also demonstrated how to add various stages to your pipeline through this tab. I encourage you to play around with the interface so you have a good sense of how everything works. I think you\u2019ll find that this is a very useful and intuitive tool for building your aggregations.<\/p>\n<p>One thing I did not cover, however, is the Stage Wizard, which you can access by clicking the <strong>Wizard<\/strong> button in the upper right corner. The wizard provides a set of templates for creating basic aggregations. Its purpose is mainly to help you get started with building an aggregation pipeline. You might find this helpful in some use cases, especially when first learning how to build aggregation pipelines. The <strong>Aggregations<\/strong> tab also includes several other features that you might want to explore.<\/p>\n<p>Regardless of the many features available on the <strong>Aggregations<\/strong> tab, it\u2019s still important that you have a foundation in how an <code>aggregate<\/code> statement works, particularly the aggregation pipeline. The better you understand these concepts, the more effectively you can use the tab\u2019s features.<\/p>\n<h2>Appendix: Preparing your MongoDB environment<\/h2>\n<p>For the examples in this article, I used MongoDB Atlas to store the data and MongoDB Compass to work with that data. This is the same approach I used for the previous articles in this series. The first of these articles explains how to set up the two environments.<\/p>\n<p>The examples in this article are based on a collection I created from the <code>sample_supplies<\/code> database available through MongoDB Atlas. This is the same data I used for the previous article, so if you set up your environment for that article, you should by all set.<\/p>\n<p>If you did not set up the environment and want to try out these examples in this article, you\u2019ll need to download the <strong>sales.json<\/strong> file and save it to a folder that you can access from within MongoDB Compass. You\u2019ll then need to take the following steps to import the data into your collection:<\/p>\n<ol>\n<li>In MongoDB Compass, connect to your cluster on MongoDB Atlas, if you\u2019re not already connected.<\/li>\n<li>In the left panel, click the <strong>Create<\/strong> <strong>database<\/strong> button (plus sign), which is located to the right of the <strong>Databases<\/strong> node.<\/li>\n<li>In the <strong>Create<\/strong> <strong>Database<\/strong> dialog box, type <strong>reports<\/strong> in the <strong>Database<\/strong> <strong>Name<\/strong> text box, type <strong>sales<\/strong> in the <strong>Collection Name<\/strong> text box, and click <strong>Create Database<\/strong>.<\/li>\n<li>After the database and collection have been created, select the <strong>sales<\/strong> collection node in the left panel if it\u2019s not already selected.<\/li>\n<li>In the main window, on the <strong>Documents<\/strong> tab, click the <strong>Add<\/strong> <strong>Data<\/strong> drop-down arrow and click <strong>Import JSON or CSV file<\/strong>.<\/li>\n<li>When your system\u2019s file manager window appears, navigate to the folder that contains the <strong>sales.json<\/strong> file, select the file, and click <strong>Select<\/strong>. Compass will load the data into the <code>sales<\/code> collection.<\/li>\n<\/ol>\n<p>That\u2019s all you need to do to try out the examples in this article. I plan to go into more detail about both importing and exporting data later in the series.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous article in this series, I demonstrated how to build and run an aggregate statement in MongoDB Shell. An aggregate statement makes it possible to group and summarize a collection\u2019s document data, as well as transform the data and control its output. For the examples in that article, I used the version of&#8230;&hellip;<\/p>\n","protected":false},"author":221841,"featured_media":104582,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[53,159161],"tags":[5618,159226],"coauthors":[6779],"class_list":["post-101454","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-featured","category-mongodb","tag-mongodb","tag-mongodbseriesrobertsheldon"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/101454","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221841"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=101454"}],"version-history":[{"count":3,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/101454\/revisions"}],"predecessor-version":[{"id":104583,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/101454\/revisions\/104583"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media\/104582"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=101454"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=101454"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=101454"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=101454"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}