In this exercise, you’ll add a stage to the pipeline after the $project
stage. The new stage will be based on the $replaceRoot
aggregate operator, which replaces input documents with output documents. In this way, you can reorder the fields as they pass through the pipeline.
To reorder the fields in the aggregation pipeline
- On the Pipeline tab of the Aggregation Editor, ensure that
$project
stage is selected, click the small down arrow to the right of the Add button, and click Add New Stage After Selected Stage.
The Aggregation Editor adds a new tab to the right of the 3: $project tab and makes the new tab active. As before, the new stage is based on the$match
operator, so the tab is named 4: $match.
- On the new tab, select the $replaceRoot option from the Operator drop-down. The
$replaceRoot
operator lets you change the order of the fields in the pipeline.
When you select the $replaceRoot option, the Aggregation Editor adds an expression that starts with thenewRoot
keyword, followed by a placeholder. You must start your expression with thenewRoot
keyword, along with a trailing colon. The subexpression that follows should be enclosed in curly braces.
- In the editor window, delete the subexpression placeholder text and type the following code after the
newRoot
operator and its trailing colon:
{state: "$state", total: "$total"}
The new code includes two elements, one for the state
field and one for the total
field. The value assigned to each field is the original field, with the name preceded by the dollar sign, which is necessary when specifying a field as a value. The subexpression ensures that the state
field appears first, followed by the total
field. The complete expression should now look like the following code:
{ newRoot: {state: "$state", total: "$total"} }
- In the Stage Input pane, click the Execute button. Studio 3T runs the pipeline for the first three stages and returns the data to that pane. This is the data that is used as input for the
$replaceRoot
stage. - In the StageOutput pane, click the Execute button. This will execute the pipeline up to and including the fourth stage. The following figure shows part of the results, with the
state
field listed first, followed by thetotal
field.
- Go to the Query Code tab. Verify that the pipeline includes the $replaceRoot operator and its expression.
- Go to the Pipeline tab. Verify that the pipeline includes the $replaceRoot stage.
- In the Pipeline output pane, click the Refresh button to update the results.
- 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. You’ll be modifying the statement by changing the sort order.