Exercise 3: Adding and removing fields in the aggregation pipeline

In this exercise, you will add the third stage to the pipeline. The stage is based on the $project aggregate operator, which lets you reshape the documents in the pipeline.

In this case, you will use the stage to exclude the _id field and add a new field that contains the _id values.

To add and remove fields in the aggregation pipeline

1. On the Pipeline tab of the Aggregation Editor, ensure that the Stage 2 row is selected (the $group 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 3 tab to the right of the Stage 2 tab and makes the new tab active. As with the first two stages, the editor selects the $match operator for the new stage.

2. On the Stage 3 tab, select the $project option from the Filter drop-down list in the upper left corner. The $project operator lets you specifically include and exclude fields in the pipeline.

Aggregation Editor

When you select the $project option, the Aggregation Editor adds the initial curly braces and a placeholder comment.

3. In the editor window, delete the placeholder and type the following expression between the curly braces:

_id: 0,
city: "$_id",
total: 1

The expression includes three arguments, separated by commas. Each argument is its own expression.

  • The first argument specifies that the _id field should be suppressed, as indicated by the 0 value. If you want to explicitly include a field, you must set the value to 1.
  • The second argument adds a new column named city and sets its values to the _id field. Essentially, you’re changing the name of the _id field to city.
  • The third argument specifies that the total column should be included in the pipeline.

4. In the Stage Output pane in the bottom section, click the Execute button. This will execute the pipeline up to and including the third stage. The following figure shows part of the results, as they appear in Table View.

output

Notice that the _id field is still included in this view. However, if you switch to JSON View, you can see that the results include only the total and city fields.

Stage output Json view

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

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

7. 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