- 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
$lookup
stage uses theprodId
field in theorders
collection to “join” documents in theinventory
collection that have matchingprodId
fields. - The matching documents are added as an array in the
inventoryDocs
field. - The
$project
stage selects a subset of the available fields. - The
$unwind
stage converts theprice
field from an array to a scalar value.
The documents in the sales
view are: