对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

使用视图连接两个集合

使用 $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> }]
给本页内容打分