使用 $lookup 为两个集合创建视图。应用程序可以查询视图,而无需构建或维护复杂的管道。
例子
本页上的示例使用 sample_mflix示例数据集 的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
创建连接视图
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" } } } ] )
在示例中:
查询视图
查询评论最多的五部电影的视图:
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> } ]