$out

The `$out` stage in an aggregation pipeline allows you to write the resulting documents of the pipeline into a specified collection. It is commonly used to save the output of complex aggregation operations for further use or analysis.

Syntax

{
  $out: "<outputCollection>"
}

Parameters

outputCollectionstringrequired

The name of the collection where the aggregation result will be stored.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": {
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 }
    ]
  }
}

Writing aggregation results to a new collection

Write stores with total sales greater than 30,000 into a new collection called highSales.

This query filters and outputs matching documents to a new collection.

Query:

db.stores.aggregate([
  {
    $match: {
      "sales.salesByCategory.totalSales": { $gt: 30000 }
    }
  },
  {
    $out: "highSales"
  }
])

Output:

Collection 'highSales' created with matching documents.

Writing processed data to another collection

Extract promotion events and write them into a collection named promotionEventsSummary.

This query projects specific fields and writes them to a new collection.

Query:

db.stores.aggregate([
  {
    $project: {
      eventName: 1,
      promotionalDates: 1,
      "discounts.categoryName": 1
    }
  },
  {
    $out: "promotionEventsSummary"
  }
])

Output:

Collection 'promotionEventsSummary' created with projected data.

Related