In this exercise, you’ll add a stage to the aggregation pipeline that uses the $merge
aggregate operator to save the pipeline results to a new collection.
To write the pipeline results to the new collection
- On the Pipeline tab of the Aggregation Editor, right-click the
$sortByCount
pipeline stage, and then click Add New Stage After Selected Stage. - On the new tab, select the $merge option from the Operator drop-down list. The
$merge
operator writes the stage’s output to the specified collection. - In the editor window, replace the placeholder text and curly braces with the following code:
{ into: { db: "reference", coll: "interests" }, whenMatched: "replace" }
The operator expression includes two fields (arguments):
- The
into
field is mandatory and specifies the output collection, which in this case is theinterests
collection in thereference
database. - The
whenMatched
field determines the operator’s behavior when the source document matches the target document. In this case, thereplace
value is specified, indicating that duplicate documents should be replaced.
- Run the Stage Input and Stage Output tabs. The tabs should return identical results. The following figure shows those results as they appear in Table View.
Be aware that when you run the stage output, you are carrying out the actual operation, which means the pipeline output will be added to the target collection. If the collection doesn’t exist, it will be created. If the collection does exist, the operation will overwrite matching documents in that collection because the whenMatched
option is set to replace
.
- Go to the Pipeline tab and click the Execute button on the Aggregation Editor toolbar. Studio 3T runs the aggregate statement and returns the results to the Pipeline output pane at the bottom of the tab, as shown in the following figure.
- As expected, the pipeline returns the list of interests and provides the total number of documents in each group. The operation will once again write the pipeline output to the target collection, replacing any matching documents.
- Click Save on the Aggregation Editor toolbar to save your changes.
- In the Connection Tree, right-click the top-level connection node, and then click Refresh All.
- Expand the reference database node and, if necessary, expand the Collections node.
- Double-click the interests collection node to open the interests collection in a new tab, which is shown in the following figure.
- Close the Aggregation tab and the interests tab and then close Studio 3T.