In this exercise, you’ll add the third and final 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
- On the IntelliShell tab, ensure that the aggregate statement you updated in the previous exercise is still entered at the command prompt.
- After the closing curly brace for the second stage, type a comma and insert a new line.
- On the new line after the second stage, add the following stage to the pipeline:
{ "$sort": { "total": -1 } }
This stage uses the $sort
operator to sort the documents in the pipeline based on the values in the total
field. The operator expression specifies a value of -1
for the sort order, which means the results will be sorted in descending order, with the highest value first. The aggregate statement should now look like the following code:
db.customers.aggregate( [ { "$match": { "dob": { "$lt": ISODate("1970-01-01T00:00:00.000Z") } } }, { "$group": { "_id": "$address.state", "total": { "$sum": "$transactions" } } }, { "$sort": { "total": -1 } } ] );
- On the IntelliShell toolbar, click the Execute button. Studio 3T runs the
aggregate
statement and displays the results in the lower pane, as shown in the following figure.
![](https://studio3t.com/wp-content/uploads/2022/02/l1e3queryresults.png)
Notice that the results are now sorted by the total
values, starting with the state with the most transactions and then working down.
- Leave the IntelliShell tab open and the existing statement in place for the next exercise.