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

뷰를 사용하여 두 컬렉션에 참여

두 컬렉션에 대한 뷰를 생성하려면 $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 필드에 배열로 추가됩니다.

  • 단계에서는 각 영화의 댓글 $project 수인 를 포함하여 사용 가능한 필드의 하위 집합을 선택합니다.numComments

댓글이 가장 많은 영화 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> }
]

돌아가기

생성 및 쿼리

이 페이지의 내용