In this exercise, you will add the fifth and last stage to the pipeline. The stage is based on the $sort
aggregate operator, which lets you sort the documents in the pipeline, based on one or more fields.
To sort the documents in the aggregation pipeline
1. On the Pipeline tab of the Aggregation Editor, ensure that the Stage 4 row is selected (the $replaceRoot
row), click the small down arrow to the right of the Add button, and click Add New Stage After Selected Stage.
The Aggregation Editor adds the Stage 5 tab to the right of the Stage 4 tab and makes the new tab active.
2. On the Stage 5 tab, select the $sort option from the operator drop-down list in the upper left corner.
When you select the $sort option, the Aggregation Editor adds two lines of placeholder comments.
3. In the editor window, delete the placeholders and type the following expression between the curly braces:
total: -1
The expression specifies that the documents should be sorted by the total
field in descending order, as indicated by the -1
value.
If you want to sort a field in ascending order, you must specify the 1
value.
4. In the Stage Output pane in the bottom section, click the Execute button.
This will execute the pipeline up to and including the fifth stage. The following figure shows part of the results, as they appear in Table View.
The results are now sorted by the total
field, with the highest amounts listed first. As you can see, most transactions come out of Sacramento, followed by Los Angeles.
5. Go to the Query Code tab. Verify that the code includes all five pipeline operators and their expressions, as shown in the following figure.
You can copy the code to the clipboard or open it in IntelliShell, where you can edit it further.
6. Go to the Pipeline tab. Verify that the pipeline includes the Stage 5 row and that the row contains the $sort
operator and its expression. The tab should now look like the one in the following figure.
7. Close the Aggregation tab. If prompted to save your changes, click No.
8. Close Studio 3T.