In this exercise, you’ll add a stage to the aggregation pipeline after the $replaceRoot
stage. The new stage will convert the data in the population
field from string values to integers. As part of this process, you’ll first remove the commas from the string values so you do not receive an error when trying to convert the values to integers.
To convert the string field to integers
- On the Pipeline tab of the Aggregation Editor, right-click the
$replaceRoot
pipeline stage, and then click Add New Stage After Selected Stage. - On the new tab, select the $set option from the Operator drop-down list. The $set operator lets you add new fields to the pipeline or overwrite existing ones.
- In the editor window, replace the placeholder text and curly braces with the following code:
{ population: { $toInt: { $replaceAll: { input: { $first: "$population" }, find: ",", replacement: "" } } } }
The $set
expression overwrites the existing population
field and updates the data in two ways. The first is by using the $replaceAll
operator to remove the commas from the string values so they can be converted to integers. The operator takes three arguments:
- The
input
argument uses the$first
operator to specify that the field values should be based on the first element in the population array. - The
find
argument tells the$replaceAll
operator to locate all commas in the string value. - The
replacement
argument indicates that the commas should be replaced with an empty string, thus removing each comma from the string values.
The $set
expression then uses the $toInt
operator to convert the output from the $replaceAll
operator to integers. Integers can be useful when performing calculations or sorting documents, as you’ll see in the following exercises.
- In the Stage Input pane, click the Execute button. Studio 3T runs the pipeline for all stages up to but not including the
$set
stage. - In the Stage Output pane, click the Execute button. This will execute the pipeline up to and including the
$set
stage. The following figure shows part of the results, as they appear in Tree View.
The population
data is now included as an Int32
field in the primary document, rather than being a string element in an array or string field in an array’s embedded document.
- 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 building on this statement by adding another pipeline stage.