Exercise 4: Changing the field order in the aggregation pipeline

In this exercise, you will add the fourth stage to the pipeline. The stage is based on the $replaceRoot aggregate operator, which replaces input documents with output documents.

In this way, you can reorder the fields as they appear in the pipeline.

To change the field order in the aggregation pipeline

1. On the Pipeline tab of the Aggregation Editor, ensure that the Stage 3 row is selected (the $project 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 4 tab to the right of the Stage 3 tab and makes the new tab active.

2. On the Stage 4 tab, select the $replaceRoot option from the Filter 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 the newRoot operator, followed by a placeholder.

You must precede your expression with the newRoot operator, along with a trailing colon. The expression itself should be enclosed in curly braces.

3. In the editor window, delete the placeholder and type the following expression after the newRoot operator and its trailing colon:

{city: "$city", total: "$total"}

The new code includes two elements, one for the city 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. This ensures that the city field appears first, followed by the total field.

The complete expression should now look like the following code:

{
  newRoot: {city: "$city", total: "$total"}
}

4. In the Stage Output pane in the bottom section, 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 city field listed first, followed by the total field.

Execute output

5. Go to the Query Code tab. Verify that the code includes the $replaceRoot operator and its expression.

6. Go to the Pipeline tab. Verify that the pipeline includes the Stage 4 row and that the row contains the $replaceRoot operator and its expression.

Leave the Aggregation tab and aggregate statement in place for the next exercise.

Log in

Log in to your Studio 3T Academy account

Forgot password?

Don't have an account yet? Sign up
Sign up

Start learning MongoDB today. All fields are mandatory.

By signing up for a course, you agree to the 3T Software Labs Privacy Policy.


Already have an account? Log in