Merge Similar Collections with $unionWith
Explore how to use MongoDB's $unionWith operator to merge documents from multiple collections with similar schemas. Understand how to combine orders and cancelled orders collections to perform unified aggregations and calculate total revenue. This lesson teaches you to manage distributed datasets efficiently with aggregation pipelines.
We'll cover the following...
The $unionWith operator in MongoDB is a powerful feature that allows us to combine the results of multiple collections into a single aggregation pipeline. This is especially useful when we have multiple collections with similar schemas and want to analyze or report on them as if they were a single dataset.
Setting up
Up until now, our database does not contain similar collections. Let's build up a use case for this. The tech team has decided to keep cancelled orders in a separate collection, instead of keeping them in the orders collection. The following query does this:
...