Community Day Trivia #26: In MongoDB 4.2, what aggregation stages can be used to save result documents to a collection?

We’ll be posting trivia challenges throughout the Community Day event!

The best answer for each challenge will be marked as a solution and earn the poster a promo code for $100 of Atlas credits and a Community Day 2021 Trivia Winner forum badge that can also be used as a title on the forums.

A great answer will include some information such as a link to more information or a tip on how you figured out the solution.

You can help us decide the best answer to a trivia challenge by liking great responses! To give everyone a chance at earning Atlas credits, we will use “have you already had a trivia solution accepted” to break ties in favour of those who haven’t had a solution yet.

In MongoDB 4.2, what aggregation stages can be used to save result documents to a collection?

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.

3 Likes

Welcome to the MongoDB Community Forums @nayan_Gajera and thanks for the great answer!

I’ll be following up with a $100 Atlas promo code :slight_smile:

Regards,
Stennie

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.