2 つのコレクションのビューを作成するには、$lookup を使用します。アプリケーションは、複雑なパイプラインを構築または維持することなく、ビューに対してクエリを実行できます。
例
...include:: /includes/sample-data-usage.rst
結合ビューの作成
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" } } } ] )
この例では、次のことが行われます。
ビューをクエリする
最もコメントが多い 5 つの映画のビューをクエリします。
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> } ]