MongoDB Aggregation $out

MongoDB Tutorial

MongoDB Aggregation $out 📤 (Write Pipeline Results)

In MongoDB, the $out stage is used in an Aggregation Pipeline to write the final result into a collection instead of returning it to the screen.

👉 Think of $out as “save aggregation result to a collection”.


What does $out do?

  • Writes aggregation output to a new or existing collection

  • Replaces the target collection if it already exists

  • Must be the last stage in the pipeline

  • Useful for reports, backups, materialized views


Basic Syntax



 

📌 The output collection will be created automatically if it doesn’t exist.


1️⃣ Simple $out Example

Copy all students into a new collection



 

✅ Creates students_backup collection with all documents from students.


2️⃣ $out with $match

Save only BA students



 


3️⃣ $out with $group (Reports)

Create a report: total students per course



 

📌 Now course_report stores precomputed results.


4️⃣ $out with $project

Store cleaned output



 


5️⃣ Verify Output Collection



 


$out vs $merge

$out $merge
Replaces entire collection Inserts / updates selectively
Deletes old data Preserves existing data
Simple use cases Advanced sync use cases

📌 Use $merge when you don’t want full replacement.


SQL Comparison

SQL



 

MongoDB



 


Important Rules ⚠️

  • $out must be the last stage

  • Target collection is fully replaced

  • Requires write permission

  • Cannot output to the same collection you’re reading from


Common Mistakes ❌

  • Using $out in the middle of pipeline

  • Accidentally overwriting important collections

  • Expecting $out to append data


Best Practices 👍

  • Use $out for reporting & backups

  • Prefer $merge for incremental updates

  • Always double-check output collection name


Quick Recap 🧠


 

You may also like...