MongoDB $out Example | The MongoDB Aggregation Pipeline

We show you how to use the MongoDB $out stage to output documents of an aggregation query to a new collection.

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:

$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

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

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. 

$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

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
    }
);