Merge Similar Collections with $unionWith
Learn to use the $unionWith operator in MongoDB to merge documents from multiple collections into a single aggregation pipeline, enabling combined analysis and reporting on similar datasets.
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:
db.orders.aggregate([ // Picking cancelled orders from orders collection{$match: {status: "Cancelled"}},{$merge: {into: "cancelledOrders", // Adding cancelled orders to a new collectionwhenMatched: "keepExisting",whenNotMatched: "insert"}}]),db.orders.deleteMany({ // Deleting cancelled orders from orders collectionstatus: "Cancelled"}),db.cancelledOrders.find().limit(5) // Printing first 5 orders from the new collection
...