- Introduction to MongoDB >
- Databases and Collections >
- Views >
- Use a View to Join Two Collections
Use a View to Join Two Collections¶
On this page
You can use $lookup to create a view over two collections
and then run queries against the view. Applications can query the view
without having to construct or maintain complex pipelines.
Example¶
Create two sample collections, inventory and orders:
Create a Joined View¶
This command uses db.createView() to create a new view named
sales based on the orders collection:
In the example:
- The
$lookupstage uses theprodIdfield in theorderscollection to “join” documents in theinventorycollection that have matchingprodIdfields. - The matching documents are added as an array in the
inventoryDocsfield. - The
$projectstage selects a subset of the available fields. - The
$unwindstage converts thepricefield from an array to a scalar value.
The documents in the sales view are: