MongoDB Aggregation $out

MongoDB Aggregation $out
In MongoDB, $out is an aggregation stage used to write the result of an aggregation pipeline into a new collection.
Think of $out as:
“Save aggregation result permanently”
What is $out?
$outtakes the final result of an aggregation pipelineStores it in a collection
The target collection can be:
Newly created
Or overwritten if it already exists
1️⃣ Basic Syntax
$out must be the LAST stage in the pipeline.
2️⃣ Simple Example (Most Common)
Scenario
You have a users collection and want to store only users from Delhi into a new collection.
Source Collection: users
Result:
Creates a new collection:
delhiUsersStores filtered documents permanently
3️⃣ Verify Output Collection
4️⃣ $out with Grouping (Interview Favorite)
Scenario
Count users by city and store result.
Output Collection: usersByCity
5️⃣ $out Overwrites Existing Collection
If the output collection already exists:
MongoDB drops and recreates it.
📌 Important Interview Point
❌ Existing data is lost
✔ Indexes are removed
✔ Only aggregation result remains
6️⃣ $out vs $merge (Very Important)
| Feature | $out | $merge |
|---|---|---|
| Overwrites collection | ✅ Yes | ❌ Optional |
| Inserts new data | ❌ No | ✅ Yes |
| Updates existing docs | ❌ No | ✅ Yes |
| Safer for production | ❌ | ✅ |
$mergeis preferred in production systems.
7️⃣ When to Use $out?
✔ Creating summary collections
✔ Data transformation pipelines
✔ Reporting / analytics
✔ Backup of processed data
✔ Exam & interview questions
8️⃣ Restrictions & Rules
✔ $out must be last stage
✔ Cannot be used inside transactions
✔ Requires write permission
✔ Drops target collection if exists
Key Points (Very Important for Exams & Interviews)
✔ $out writes aggregation result to a collection
✔ Creates new collection automatically
✔ Overwrites existing collection
✔ Must be last pipeline stage
✔ Not recommended for live production updates
Common Interview Questions
Q1. What does $out do in MongoDB?
👉 Saves aggregation results into a collection
Q2. Can $out update existing documents?
👉 ❌ No
Q3. What happens if output collection exists?
👉 It is dropped and recreated
Q4. Which is safer: $out or $merge?
👉 $merge
Summary
That’s everything you need to know about MongoDB Aggregation
$out.
