0
0
MongoDBquery~5 mins

$out and $merge for writing results in MongoDB

Choose your learning style9 modes available
Introduction

These operators help you save the results of your data processing into a new or existing collection. This way, you can keep the results for later use.

When you want to save the filtered or transformed data into a new collection for reports.
When you need to update an existing collection with new or changed data after processing.
When you want to combine results from multiple documents into one collection for easier access.
When you want to create backups of processed data automatically.
When you want to prepare data for another application by storing it in a specific collection.
Syntax
MongoDB
db.collection.aggregate([
  { $out: "targetCollection" }
])

// or

db.collection.aggregate([
  { $merge: { into: "targetCollection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])

$out replaces the entire target collection with the aggregation results.

$merge can update existing documents or insert new ones based on matching fields.

Examples
This saves all sales with status 'A' into a new collection called 'activeSales'.
MongoDB
db.sales.aggregate([
  { $match: { status: "A" } },
  { $out: "activeSales" }
])
This groups orders by customer and saves totals into 'customerTotals', updating existing entries or adding new ones.
MongoDB
db.orders.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $merge: { into: "customerTotals", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])
Sample Program

This finds all products in the 'Books' category and merges them into 'booksCollection'. Existing documents are replaced, new ones are inserted.

MongoDB
db.products.aggregate([
  { $match: { category: "Books" } },
  { $merge: { into: "booksCollection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])
OutputSuccess
Important Notes

Use $out when you want to replace the whole collection with new data.

Use $merge when you want to update or add data without deleting existing documents.

Both operators require write permissions on the target collection.

Summary

$out saves aggregation results by replacing the target collection.

$merge saves results by updating or inserting documents based on matching keys.

These operators help keep processed data for future use or sharing.