TExcelTAD
Home › MongoDB › Aggregation $out and $merge

Aggregation $out and $merge

Normally an aggregation returns its results to the client. The stages $out and $merge instead write the results into a collection. They must be the last stage of the pipeline.

Stage Writes Existing target collection
$out all results to a collection replaced completely (atomically)
$merge results into a collection combined document by document: insert, replace, merge, keep or fail

Typical uses are reports that are expensive to compute, nightly summaries and materialised views: precomputed collections that dashboards read cheaply.

$out

mongosh · try it yourself
db.orders.aggregate([
  { $match: { status: { $ne: 'cancelled' } } },
  { $group: { _id: '$customerId', orders: { $sum: 1 }, spent: { $sum: '$total' } } },
  { $out: 'customer_totals' }
]);

print(db.customer_totals.countDocuments());
print(db.customer_totals.find({ spent: { $gte: 130 } }).sort({ spent: -1 }).toArray());
9
[
  { _id: 5, orders: 3, spent: 209 },
  { _id: 3, orders: 3, spent: 178 },
  { _id: 1, orders: 3, spent: 142.5 },
  { _id: 11, orders: 2, spent: 131 }
]

The aggregation itself returned no documents; everything went into customer_totals, which you can query like any other collection.

Running the pipeline again replaces the whole collection, so documents that are no longer produced disappear:

mongosh · try it yourself
db.orders.aggregate([{ $match: { status: 'cancelled' } }, { $out: 'report' }]);
print('first run: ', db.report.find().toArray().map(d => d._id));
db.orders.aggregate([{ $match: { status: 'shipped' } }, { $out: 'report' }]);
print('second run:', db.report.find().toArray().map(d => d._id));
first run:  [ 1006, 1017 ]
second run: [ 1010, 1012, 1013 ]

$out can also write to another database: { $out: { db: 'reporting', coll: 'customer_totals' } }.

$merge

$merge updates a collection incrementally. For each result document it looks for a target document with the same _id (or the fields given in on, which need a unique index) and decides what to do:

Option Values
whenMatched 'replace', 'merge' (default: combine fields), 'keepExisting', 'fail', or an update pipeline
whenNotMatched 'insert' (default), 'discard', 'fail'

Here a monthly sales collection is maintained. The first run summarises March, the second run adds April without touching March:

mongosh · try it yourself
function summarise(from, to) {
  db.orders.aggregate([
    { $match: { date: { $gte: from, $lt: to }, status: { $ne: 'cancelled' } } },
    { $group: {
        _id: { $dateToString: { format: '%Y-%m', date: '$date' } },
        orders: { $sum: 1 },
        revenue: { $sum: '$total' }
    } },
    { $merge: { into: 'monthly_sales', whenMatched: 'replace', whenNotMatched: 'insert' } }
  ]);
}
summarise(ISODate('2026-03-01T00:00:00Z'), ISODate('2026-04-01T00:00:00Z'));
print(db.monthly_sales.find().sort({ _id: 1 }).toArray());
summarise(ISODate('2026-04-01T00:00:00Z'), ISODate('2026-05-01T00:00:00Z'));
print(db.monthly_sales.find().sort({ _id: 1 }).toArray());
[ { _id: '2026-03', orders: 7, revenue: 385.5 } ]
[
  { _id: '2026-03', orders: 7, revenue: 385.5 },
  { _id: '2026-04', orders: 5, revenue: 174.5 }
]

Merging fields into existing documents

With whenMatched: 'merge', fields from the pipeline are added to the existing documents. This writes a computed unitsSold straight into the product documents:

mongosh · try it yourself
db.orders.aggregate([
  { $match: { status: 'delivered' } },
  { $unwind: '$items' },
  { $group: { _id: '$items.productId', unitsSold: { $sum: '$items.qty' } } },
  { $merge: { into: 'products', whenMatched: 'merge', whenNotMatched: 'discard' } }
]);
db.products.find({ unitsSold: { $gte: 3 } }, { name: 1, stock: 1, unitsSold: 1 }).sort({ _id: 1 }).forEach(p => print(p));
{ _id: 1, name: 'Espresso Beans', stock: 40, unitsSold: 3 }
{ _id: 2, name: 'House Blend', stock: 65, unitsSold: 3 }
{ _id: 6, name: 'Green Sencha', stock: 30, unitsSold: 3 }
{ _id: 7, name: 'Earl Grey', stock: 80, unitsSold: 4 }
{ _id: 15, name: 'Paper Filters (100)', stock: 120, unitsSold: 3 }
{ _id: 17, name: 'Dark Chocolate Bar', stock: 75, unitsSold: 10 }
{ _id: 19, name: 'Salted Pretzels', stock: 40, unitsSold: 3 }

Warning: $out drops whatever was in the target collection, including documents written by others. Double-check the name: { $out: 'orders' } on the orders collection would replace your orders with the report!

Test yourself

Where in a pipeline can $out appear?

  1. Anywhere
  2. Only first
  3. Only last
  4. Only after $group

You need to add new daily figures to a report collection without deleting older days. Which stage?

  1. $out
  2. $merge
  3. $addFields
  4. $lookup