두 컬렉션에 대한 뷰를 생성하려면 $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" } } } ] )
예시:
뷰 쿼리
댓글이 가장 많은 영화 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> } ]