MongoDB Aggregation $out
MongoDB Aggregation $out 📤 (Write Pipeline Results)
👉 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 ⚠️
-
$outmust 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
$outin the middle of pipeline -
Accidentally overwriting important collections
-
Expecting
$outto append data
Best Practices 👍
-
Use
$outfor reporting & backups -
Prefer
$mergefor incremental updates -
Always double-check output collection name
