Try Studio 3T for Free
  1. Knowledge Base
  2. MongoDB Tutorials
  3. MongoDB $out Example | The MongoDB Aggregation Pipeline

MongoDB $out Example | The MongoDB Aggregation Pipeline

This is Stage 3 of a three-part aggregation query example that uses the $lookup, $project$out stages and Studio 3T. Download it here.

The $out stage

The $out stage is used to export output documents of an aggregation query to a new collection, making it the last stage to be applied in the aggregation pipeline.

To illustrate how a full aggregation query works with an $out stage, we recommend building other stages first:

$out syntax

Once 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

Picking up from our $project stage example, we are now ready to add a third and final stage to our pipeline.

Click on the green plus icon. This will open a new tab called Stage 3.

Choose $out from the dropdown menu. 

MongoDB out stage

 

All we need to do is replace <output-collection> – make sure to keep the quotes! – and type the collection name where we’d like to store our aggregation query’s output documents. 

Let’s type customers-affordable-housing and click on the play button or Execute the entire pipeline.

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. 

New collection created by $out

$out in IntelliShell

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. 

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

Now that you’ve reached the end of our three-part aggregation query example:

Updated on December 5, 2019

Was this article helpful?

Related Articles