Docs 菜单
Docs 主页
/ /
/ / /

使用视图连接两个集合

使用 $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" }
}
}
] )

在示例中:

  • $match 阶段将 movies 集合过滤为从 2014 开始发布的文档。

  • $lookup 阶段使用 movies 集合中的 _id 字段来连接 comments 集合中具有匹配 movie_id 字段的文档。

  • 匹配的文档将作为数组添加到 movieComments 字段中。

  • $project 阶段选择可用字段的子集,包括 numComments,即每部电影的评论数。

查询评论最多的五部电影的视图:

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> }
]

后退

创建和查询

在此页面上