Use $lookup to create a view over two collections.
Applications can query the view without constructing or
maintaining complex pipelines.
Example
..include:: /includes/sample-data-usage.rst
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> } ]