Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
/ / /

ビューを使用して 2 つのコレクションを結合

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

この例では、次のことが行われます。

  • $matchステージでは、movies コレクションを2014 以降にリリースされたドキュメントでフィルタリングします。

  • $lookupステージでは、_id moviesコレクションの フィールドを使用して、comments フィールドと一致するmovie_id コレクション内のドキュメントを結合します。

  • 一致するドキュメントは、movieComments フィールドに配列として追加されます。

  • $projectnumCommentsステージでは、各映画のコメント数である を含む使用可能なフィールドのサブセットが選択されます。

最もコメントが多い 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> }
]

戻る

作成とクエリ

項目一覧