How to combine(union all) two collections in one collection?

To combine (union all) two collections in MongoDB, you can use the aggregation framework with the following stages: $match, $project, and $unionWith.

Here is a step-by-step guide on how to accomplish this:

1. Connect to your MongoDB database using a MongoDB driver for your preferred programming language.

2. Define the two collections that you want to combine. Let's call them collection1 and collection2.

3. Use the $match stage to filter the documents from the collections if needed. This stage is optional and can be skipped if you want to combine all documents from both collections.

const matchStage = { $match: { /* filter criteria */ } };

4. Use the $project stage to add a new field to each document that distinguishes the source collection. This step is useful to keep track of which collection the document comes from.

const projectStage1 = { $addFields: { collection: "collection1" } };
const projectStage2 = { $addFields: { collection: "collection2" } };

5. Use the $unionWith stage to combine the two collections.

const unionStage = { $unionWith: "collection1" };

6. Execute the aggregation pipeline, combining all the stages together.

const combinedCollection = await db.collection1.aggregate([
  matchStage,
  projectStage1,
  unionStage,
  matchStage,
  projectStage2,
]).toArray();

The above code will return an array with documents from both collection1 and collection2, combined into a single collection. Each document will have an additional field called collection, indicating the source collection.

Remember to replace db.collection1 with the actual collection names and adjust the filter criteria in the $match stages as per your requirement.

By following these steps, you will be able to combine (union all) two collections into one in MongoDB using the aggregation framework.