MongoDB Aggregation $out (original) (raw)

Last Updated : 16 Apr, 2026

The $out stage in MongoDB allows you to persist the results of an aggregation pipeline by writing them to a collection, making pre-processed data available for reporting, analytics, and future queries.

Key Features of $out

The $out stage stores the final output of an aggregation pipeline into a collection, making processed data reusable for analytics, reporting, and future queries.

**Syntax

{ $out: { db: "", coll: "" } }

Example of Using $out in MongoDB

Below is a step-by-step guide demonstrating how to use the $out stage in an aggregation pipeline.

Step 1: Aggregating Data and Writing to a New Collection

Using the sample_supplies database, the pipeline groups documents by storeLocation, calculates total items sold per location, and writes the results to the store_items_totals collection.

step1

Step1: SHOWING THE AGGREGATION PIPELINE

**Step 2: Verifying the Collection Creation

After running the query, a new collection is created, which can be verified using show collections; the store_items_totals collection appears in the sample_supplies database.

step2

Step 2: LIST OF COLLECTIONS IN THE DATABASE

**Step 3:Checking Data in the New Collection

To check whether the query is written successfully in the new collection we run the command find( ) to display the items in the collections.

stepp3

Step 3: DISPLAYING THE STORE_ITEMS_TOTALS COLLECTION

Step 4: Understanding the Output

Finally we can infer from the above image that our query is written successfully on a new collection. The results show aggregated sales data per store location.

Use Cases of MongoDB Aggregation $out

The $out stage is employed in various scenarios, including:

outVsout Vs outVsmerge

MongoDB provides both outandout and outandmerge stages for storing aggregation results, but they serve different purposes.

out∣out outmerge
Creates a new collection or replaces an existing one Updates or merges data in an existing collection
Completely replaces the existing collection Merges new data with existing documents
Storing aggregated results separately Incrementally updating or merging query results
Does not preserve existing data. Preserves existing data while merging new records.

Best Practices for Using $out

Here are some best practices of using $out: