1) $merge stage
Writes the results of the [aggregation pipeline $merge operator must be the last stage in the pipeline.
The $merge stage:
- Can output to a collection in the same or different database.
- Starting in MongoDB 4.4, $merge can output to the same collection that is being aggregated. For more information, see Output to the Same Collection that is Being Aggregated.
- Creates a new collection if the output collection does not already exist.
- Can incorporate results (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) into an existing collection.
- Can output to a sharded collection. Input collection can also be shared.
2) $out
Takes the documents returned by the aggregation pipeline and writes them to a specified collection. Starting in MongoDB 4.4, you can specify the output database.
The $out stage must be the last stage in the pipeline. The $out operator lets the aggregation framework return result sets of any size.