In this exercise, you’ll add a stage to the aggregation pipeline that uses the
$sortByCount aggregate operator to group the values in the interests field and then find the total number of documents in each group. The operator will also sort the data based on the document counts.
To group the arrays values and generate a document count
- On the Pipeline tab of the Aggregation Editor, right-click the $unwind pipeline stage, and then click Add New Stage After Selected Stage.
- On the new tab, select the $sortByCount option from the Operator drop-down list. The
$sortByCountoperator groups the documents and provides the total number of documents in each group.
- In the editor window, replace the placeholder text with the following expression:
In this case, the expression is simply the
interests field (preceded with a dollar sign), indicating that the documents should be grouped by that field.
- Run the Stage Input and Stage Output tabs. The following figure shows part of the results, as they appear in Table View.
The output data now includes only five documents, one for each array value, and the documents contain only two fields:
count. The data is sorted in descending order based on the
- Click Save on the Aggregation Editor toolbar to save your changes.
- Leave the Aggregation tab open and the existing statement in place for the next exercise.