0Pricing
MongoDB Academy · Lesson

$out and $merge: Writing Pipeline Results

Learners will direct aggregation output into a new or existing collection using $out and $merge for ETL and materialised views.

Writing Pipeline Results to Collections

By default, aggregation pipeline results are returned to the client as a cursor. Sometimes you want to persist the results into a MongoDB collection for later use as a materialised view, a reporting cache, or an ETL target. MongoDB provides two stages for this: $out, which replaces a target collection atomically, and $merge, which upserts or merges results into an existing collection.

The $out Stage

$out writes all pipeline output documents to a new or existing collection in an atomic operation. If the target collection exists, $out replaces it entirely with the new results—the old collection is dropped and the new one takes its place atomically. If it doesn't exist, MongoDB creates it. $out must be the last stage in the pipeline and returns nothing to the client.

// Materialise monthly sales summary into its own collection
db.orders.aggregate([
  { $match: { status: 'completed' } },
  { $group: {
    _id: {
      year: { $year: '$createdAt' },
      month: { $month: '$createdAt' }
    },
    totalRevenue: { $sum: '$amount' },
    orderCount: { $sum: 1 }
  }},
  { $sort: { '_id.year': 1, '_id.month': 1 } },
  { $out: 'monthly_sales_summary' }  // last stage, writes to collection
]);

All lessons in this course

  1. $lookup: Joining Collections in the Pipeline
  2. $unwind: Deconstructing Array Fields
  3. $addFields, $replaceRoot, and $mergeObjects
  4. $out and $merge: Writing Pipeline Results
← Back to MongoDB Academy