The $out
stage
The $out
stage is used to export output documents of an aggregation query to a new collection. It must always be last stage of your aggregation pipeline.
To illustrate how a full aggregation query works with an $out
stage, we recommend building other stages first:
- Stage 1 – Join two collections using
$lookup
- Stage 2 – Project fields using
$project
$out
syntax
When you’re ready to save your aggregation pipeline results, you can write the $out
command which has a straightforward syntax:
{ $out: "<output-collection>" }
Replace <output-collection>
with your desired new collection name.
$out
in Aggregation Editor
Follow the steps in our $project
stage example. To finish off our three-stage example, we will add a third and final stage to our pipeline.
Click on Add stage. Choose $out
in the Operator dropdown menu.
![MongoDB $out stage should always be the last stage in the pipeline](https://studio3t.com/wp-content/uploads/2023/10/out-example-add-out-stage-1024x351.png)
Replace the code, making sure to remove the curly braces, with:
"customers-affordable-housing"
This is the collection name where we’d like to store our aggregation query’s output documents.
Click on the Run button in the toolbar to run the full pipeline.
![Run the mongodb $out stage](https://studio3t.com/wp-content/uploads/2023/10/out-example-run-out-stage-1024x350.png)
Refresh your current database by right-clicking and choosing Refresh Selected Item or Refresh All.
You should then see your new collection on the list.
![](https://studio3t.com/wp-content/uploads/2023/10/out-example-new-collection.png)
$out
in mongo shell
To see how $out
looks like within the full MongoDB aggregation query, let’s go back to the Aggregation Editor and click on Query Code.
![The full mongo shell code with the $out stage](https://studio3t.com/wp-content/uploads/2023/10/out-example-query-code-1024x753.png)
You should see the mongo shell code with the $out
stage included, which you can easily paste into IntelliShell.
db.getCollection("customers").aggregate( [ { "$lookup" : { "from" : "housing", "localField" : "address.zip_code", "foreignField" : "Zip Code", "as" : "address.zip_code.affordable_housing_options" } }, { "$project" : { "first" : 1.0, "last" : 1.0, "address.city" : 1.0, "address.state" : 1.0, "address.zip_code.affordable_housing_options.Property Type" : 1.0, "address.zip_code.affordable_housing_options.Property Name" : 1.0, "address.zip_code.affordable_housing_options.Units" : 1.0, "address.zip_code.affordable_housing_options.Zip Code" : 1.0 } }, { "$out" : "customers-affordable-housing" } ], { "allowDiskUse" : false } );