0
0
MongodbHow-ToBeginner · 3 min read

How to Use $out in Aggregation in MongoDB: Syntax and Examples

In MongoDB aggregation, use the $out stage to write the aggregation results directly into a specified collection. It replaces the entire content of the target collection with the aggregation output. The syntax is { $out: "collectionName" } placed as the last stage in the pipeline.
📐

Syntax

The $out stage is used as the final stage in an aggregation pipeline to write the results into a collection. It takes the form:

  • { $out: "collectionName" } - writes results to the named collection.

If the collection exists, it will be replaced. If it does not exist, MongoDB creates it automatically.

mongodb
db.sourceCollection.aggregate([
  { $match: { status: "active" } },
  { $group: { _id: "$category", total: { $sum: "$amount" } } },
  { $out: "targetCollection" }
])
💻

Example

This example aggregates documents from sales collection, groups them by item, sums the quantity, and writes the results into summary collection.

mongodb
db.sales.aggregate([
  { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } },
  { $out: "summary" }
])
⚠️

Common Pitfalls

  • Placement: $out must be the last stage in the pipeline.
  • Overwrite: It replaces the entire target collection, so existing data will be lost.
  • Permissions: The user must have write permissions on the target collection.
  • Sharded Collections: $out cannot write to a sharded collection in some MongoDB versions.
mongodb
/* Wrong: $out not last stage */
db.collection.aggregate([
  { $match: { status: "active" } },
  { $out: "results" },
  { $sort: { date: -1 } }  // This will cause an error
])

/* Correct: $out last stage */
db.collection.aggregate([
  { $match: { status: "active" } },
  { $sort: { date: -1 } },
  { $out: "results" }
])
📊

Quick Reference

AspectDescription
PurposeWrite aggregation results to a collection
Syntax{ $out: "collectionName" }
PositionMust be the last stage in pipeline
EffectReplaces target collection contents
PermissionsRequires write access to target collection
Creates CollectionYes, if target does not exist

Key Takeaways

Use $out as the last stage in an aggregation pipeline to save results to a collection.
$out replaces the entire target collection with the aggregation output.
Ensure you have write permissions on the target collection before using $out.
Be careful: existing data in the target collection will be overwritten.
MongoDB creates the target collection automatically if it does not exist.