Grouping Data Across Collections
Learn to combine and group data using $lookup and $unionWith for complex queries like fetching a user’s purchases or spotting low-rated products.
We'll cover the following...
Up until now, the scope of our queries has been confined to one collection at a time. But as the data is spread across multiple collections, we may need to write queries that fetch data from more than one collection simultaneously. Suppose we need to find the product(s) bought by a specific user. To do this, we first filter the required user and retrieve their order history from the users
collection. Then, using that order history, we fetch the products purchased in each order from the orders
collection.
MongoDB doesn't allow grouping across collections in a single $group
stage directly, but we can combine (or join) collections first, then group them. Here are the supported methods:
Use
$lookup
to join collections.Use
$unionWith
to merge similar collections.
Use $lookup
to join collections
We can use $lookup
to combine data from another collection before grouping. It's safe to use ...