Search⌘ K
AI Features

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:

MongoDB
db.orders.aggregate([ // Picking cancelled orders from orders collection
{
$match: {
status: "Cancelled"
}
},
{
$merge: {
into: "cancelledOrders", // Adding cancelled orders to a new collection
whenMatched: "keepExisting",
whenNotMatched: "insert"
}
}
]),
db.orders.deleteMany({ // Deleting cancelled orders from orders collection
status: "Cancelled"
}),
db.cancelledOrders.find().limit(5) // Printing first 5 orders from the new collection

...