Use $lookup to create a view over two collections.
Applications can query the view without constructing or
maintaining complex pipelines.
Example
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Create a Joined View
db.createView( "movieComments", "movies", [ { $match: { year: { $gte: 2014 } } }, { $lookup: { from: "comments", localField: "_id", foreignField: "movie_id", as: "movieComments" } }, { $project: { _id: 0, title: 1, year: 1, numComments: { $size: "$movieComments" } } } ] )
In the example:
The
$matchstage filters themoviescollection to documents released in 2014 onward.The
$lookupstage uses the_idfield in themoviescollection to join documents in thecommentscollection that have a matchingmovie_idfield.The matching documents are added as an array in the
movieCommentsfield.The
$projectstage selects a subset of the available fields, includingnumComments, which is the count of comments for each movie.
Query the View
Query the view for the five movies with the most comments:
db.movieComments.aggregate( [ { $group: { _id: "$title", totalComments: { $sum: "$numComments" } } }, { $sort: { totalComments: -1 } }, { $limit: 5 } ] )
[ { _id: '<title>', totalComments: <num> }, { _id: '<title>', totalComments: <num> }, { _id: '<title>', totalComments: <num> }, { _id: '<title>', totalComments: <num> }, { _id: '<title>', totalComments: <num> } ]