AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

$lookup (집계 단계)

$lookup

버전 5.1에서 변경되었습니다.

Performs a left outer join to a collection in the same database to filter in documents from the foreign collection for processing. The $lookup stage adds a new array field to each input document. The new array field contains the matching documents from the foreign collection. The $lookup stage passes these reshaped documents to the next stage.

MongoDB 5.1부터 샤딩된 컬렉션에 $lookup을 사용할 수 있습니다.

서로 다른 두 컬렉션의 요소를 결합하려면 $unionWith 파이프라인 단계를 사용합니다.

중요

$lookup 성능은 다른 쿼리 성능과 마찬가지로 작업 유형과 외부 필드 의 인덱싱 여부에 따라 달라집니다. 대규모 컬렉션에서 인덱싱되지 않았거나 상관관계가 있는 하위 쿼리 $lookup 작업은 쿼리 성능을 저하시킬 수 있습니다. $lookup에 대한 의존도를 줄이려면 관련 데이터를 단일 컬렉션 에 저장 임베디드 데이터 모델 고려하세요.

For details on $lookup performance by operation type, see Performance Considerations.

다음 환경에서 호스팅되는 배포에 $lookup 사용할 수 있습니다.

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

The $lookup stage syntax:

{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to run> ],
as: <output array field>
}
}

The $lookup accepts a document with these fields:

필드
필요성
설명

필수 사항

동일한 데이터베이스에서 로컬 컬렉션에 조인할 외부 컬렉션을 지정합니다.

일부 경우에는 첫 번째 단계로 $documents 를 사용하여 from 을 pipeline 로 대체하는 것이 가능합니다. 예시는 $lookup 단계에서 $documents 단계 사용하기를 참조하세요.

MongoDB 5.1부터 from 컬렉션을 샤딩할 수 있습니다.

pipeline이 지정된 경우, 선택 사항

Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection. If an input document does not contain the localField, the $lookup treats the field as having a value of null for matching purposes.

pipeline이 지정된 경우, 선택 사항

로컬 문서의 localField와 동등성 매치를 수행하도록 외부 문서의 foreignField를 지정합니다.

If a foreign document does not contain a foreignField value, the $lookup uses a null value for the match.

옵션

Specifies variables to use in the pipeline stages. Use the variable expressions to access the fields from the local collection's documents that are input to the pipeline.

To reference variables in pipeline stages, use the "$$<variable>" syntax.

The let variables can be accessed by the stages in the pipeline, including additional $lookup stages nested in the pipeline.

  • $match 단계에서는 $expr 연산자를 사용하여 변수에 액세스해야 합니다. $expr 연산자를 사용하면 $match 구문 내에서 집계 표현식을 사용할 수 있습니다.

    The $eq, $lt, $lte, $gt, and $gte comparison operators placed in an $expr operator can use an index on the from collection referenced in a $lookup stage. Limitations:

    • 인덱스는 필드와 상수 간의 비교에만 사용할 수 있으므로 let 피연산자는 상수로 해결되어야 합니다.

      예를 들어 $a 및 상수 값 간의 비교에는 인덱스를 사용할 수 있지만, $a 및 $b 간의 비교에는 인덱스를 사용할 수 없습니다.

    • let 피연산자가 비어 있거나 누락된 값으로 확인되는 비교에는 인덱스가 사용되지 않습니다.

    • 멀티키, 부분 또는 희소 인덱스는 사용되지 않습니다.

  • Other (non-$match) stages in the pipeline do not require an $expr operator to access the variables.

localField 및 foreignField가 지정된 경우, 선택 사항

외부 컬렉션에서 실행할 pipeline을 지정합니다. pipeline은 외부 컬렉션에서 문서를 반환합니다. 모든 문서를 반환하려면 빈 pipeline: []을 지정합니다.

The pipeline cannot include the $out or $merge stages. Starting in v6.0, the pipeline can contain the Atlas Search $search stage as the first stage inside the pipeline. To learn more, see Atlas Search Support.

The pipeline cannot access fields from input documents. Instead, define variables for the document fields using the let option and then reference the variables in the pipeline stages.

To reference variables in pipeline stages, use the "$$<variable>" syntax.

The let variables can be accessed by the stages in the pipeline, including additional $lookup stages nested in the pipeline.

  • $match 단계에서는 $expr 연산자를 사용하여 변수에 액세스해야 합니다. $expr 연산자를 사용하면 $match 구문 내에서 집계 표현식을 사용할 수 있습니다.

    The $eq, $lt, $lte, $gt, and $gte comparison operators placed in an $expr operator can use an index on the from collection referenced in a $lookup stage. Limitations:

    • 인덱스는 필드와 상수 간의 비교에만 사용할 수 있으므로 let 피연산자는 상수로 해결되어야 합니다.

      예를 들어 $a 및 상수 값 간의 비교에는 인덱스를 사용할 수 있지만, $a 및 $b 간의 비교에는 인덱스를 사용할 수 없습니다.

    • let 피연산자가 비어 있거나 누락된 값으로 확인되는 비교에는 인덱스가 사용되지 않습니다.

    • 멀티키, 부분 또는 희소 인덱스는 사용되지 않습니다.

  • Other (non-$match) stages in the pipeline do not require an $expr operator to access the variables.

필수 사항

입력 문서에 추가할 새 배열 필드의 이름을 지정합니다. 새 배열 필드에는 from 컬렉션에서 매칭되는 문서가 포함됩니다. 지정된 이름이 입력 문서에 이미 존재하는 경우 기존 필드를 덮어씁니다.

To perform an equality match between a field from the input documents with a field from the documents of the foreign collection, the $lookup stage has this syntax:

{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
pipeline: [ <pipeline to run> ],
as: <output array field>
}
}

참고

이 예시 에서 pipeline 은 선택 사항이며 로컬 및 외부 동일성 단계 이후에 실행됩니다.

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, (
SELECT ARRAY_AGG(*)
FROM <collection to join>
WHERE <foreignField> = <collection.localField>
) AS <output array field>
FROM collection;

참고

이 페이지의 SQL 문은 MongoDB 집계 파이프라인 구문과 비교할 수 있도록 포함되어 있습니다. SQL 문을 실행할 수 없습니다.

MongoDB 예시는 이 페이지를 참조하세요.

MongoDB는 다음을 지원합니다.

  • 외부 컬렉션에서 파이프라인 실행하기.

  • 여러 조인 조건.

  • 상관관계가 있는 하위 쿼리와 상관관계가 없는 하위 쿼리.

In MongoDB, an uncorrelated subquery means that every input document returns the same result. A correlated subquery is a pipeline in a $lookup stage that uses the local or input collection's fields to return results correlated to each incoming document.

참고

Starting in MongoDB 5.0, for an uncorrelated subquery in a $lookup pipeline stage containing a $sample stage, the $sampleRate operator, or the $rand operator, the subquery is always run again if repeated. Previously, depending on the subquery output size, either the subquery output was cached or the subquery was run again.

MongoDB 상관 서브쿼리는 내부 쿼리가 외부 쿼리 값을 참조하는 SQL 상관 서브쿼리와 유사합니다. SQL 비연관 서브쿼리는 외부 쿼리 값을 참조하지 않습니다.

MongoDB 5.0은 상관관계가 있는 간결한 하위 쿼리도 지원합니다.

To perform correlated and uncorrelated subqueries with two collections, and perform other join conditions besides a single equality match, use this $lookup syntax:

{
$lookup:
{
from: <foreign collection>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to run on foreign collection> ],
as: <output array field>
}
}

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (
SELECT <documents as determined from the pipeline>
FROM <collection to join>
WHERE <pipeline>
);

다음 예시를 참조하세요.

버전 5.0의 신규 항목입니다.

MongoDB 5.0부터는 상관 하위 쿼리에 간결한 구문을 사용할 수 있습니다. 상관 하위 쿼리는 외부 컬렉션과 aggregate() 메서드가 실행된 '로컬' 컬렉션의 문서 필드를 참조합니다.

다음의 새로운 간결한 구문은 $expr 연산자 내부의 외부 및 로컬 필드에 대한 동등성 매치 요구 사항을 제거합니다.

{
$lookup:
{
from: <foreign collection>,
localField: <field from local collection's documents>,
foreignField: <field from foreign collection's documents>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to run> ],
as: <output array field>
}
}

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, <output array field>
FROM localCollection
WHERE <output array field> IN (
SELECT <documents as determined from the pipeline>
FROM <foreignCollection>
WHERE <foreignCollection.foreignField> = <localCollection.localField>
AND <pipeline match condition>
);

이 예시를 참조하세요.

If performing an aggregation that involves multiple views, such as with $lookup or $graphLookup, the views must have the same collation.

You cannot include the $out or the $merge stage in the $lookup stage. That is, when specifying a pipeline for the foreign collection, you cannot include either stage in the pipeline field.

{
$lookup:
{
from: <collection to join>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to execute on the foreign collection> ], // Cannot include $out or $merge
as: <output array field>
}
}

Starting in MongoDB 6.0, you can specify the Atlas Search $search or $searchMeta stage in the $lookup pipeline to search collections on the Atlas cluster. The $search or the $searchMeta stage must be the first stage inside the $lookup pipeline.

For example, when you Join Conditions and Subqueries on a Foreign Collection or run Correlated Subqueries Using Concise Syntax, you can specify $search or $searchMeta inside the pipeline as shown below:

To see an example of $lookup with $search, see the Atlas Search tutorial Run an Atlas Search $search Query Using $lookup.

Starting in MongoDB 5.1, you can specify sharded collections in the from parameter of $lookup stages.

샤딩된 컬렉션을 대상으로 하는 동안 트랜잭션 내에서 $lookup 단계를 사용할 수 없습니다.

참고

버전 7.0.17부터 7.0의 패치 버전에 대해 슬롯 기반 쿼리 실행 엔진 더 이상 기본값 으로 활성화되지 않습니다. 쿼리에서 슬롯 기반 쿼리 실행 엔진 사용하려면 8.0 버전으로 업그레이드 하세요. 기본값 으로 활성화되어 있습니다.

Starting in version 6.0, MongoDB can use the slot-based execution query engine to execute $lookup stages if all preceding stages in the pipeline can also be executed by the slot-based execution engine and none of the following conditions are true:

  • The $lookup operation executes a pipeline on a foreign collection. To see an example of this kind of operation, see Join Conditions and Subqueries on a Foreign Collection.

  • $lookup의 localField 또는 foreignField는 숫자 구성 요소를 지정합니다. 예시: { localField: "restaurant.0.review" }

  • 파이프라인에서 $lookup의 from 필드는 뷰 또는 샤드 컬렉션을 지정합니다.

자세한 내용은 $lookup 최적화를 참조하세요.

$lookup 성능은 수행되는 작업 유형에 따라 달라집니다. 다양한 $lookup 작업에 대한 성능 고려 사항은 다음 표를 참조하세요.

$lookup 작업
성능 고려 사항
  • $lookup 연산은 단일 조인으로 동등성 매치를 수행하고, 외부 컬렉션에 foreignField에 대한 인덱스가 포함된 경우 성능이 더 우수합니다.

    중요한: foreignField에 대한 지원 인덱스가 없는 경우 단일 조인으로 동등성 매치를 수행하는 $lookup 작업의 성능이 저하될 가능성이 있습니다.

  • $lookup 연산은 관련 없는 하위 쿼리를 포함하며, 내부 파이프라인이 외부 컬렉션의 인덱스를 참조할 수 있을 때 성능이 더 우수합니다.

  • MongoDB는 소스 컬렉션과 외부 컬렉션 사이에 관계가 없기 때문에 쿼리를 캐싱하기 전에 $lookup 하위 쿼리를 한 번만 실행하면 됩니다. 하위 쿼리는 소스 컬렉션의 값을 기반으로 하지 않습니다. 이 동작은 $lookup 작업의 후속 실행에 대한 성능을 향상시킵니다.

  • $lookup 작업은 연관된 하위 쿼리를 포함하며, 외래 컬렉션에 foreignField에 대한 인덱스가 포함되어 있을 때 성능이 더 우수합니다.

  • 파이프라인이 많은 수의 문서를 $lookup 쿼리에 전달하는 경우 다음 전략을 사용하면 성능이 향상될 수 있습니다.

    • MongoDB가 $lookup 쿼리에 전달하는 문서 수를 줄입니다. 예를 들어 $match 단계에서 더 엄격한 필터를 설정합니다.

    • 데이터의 스키마를 재검토하여 사용 사례에 적합한지 확인합니다.

일반적인 성능 전략은 인덱싱 전략 및 쿼리 최적화를 참조하세요.

이 페이지의 예시는 sample_mflix 데이터 세트의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB 배포서버에 로드하는 방법에 대한 자세한 내용은 샘플 데이터세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우, 이 페이지의 예시를 실행하려면 데이터베이스를 제거하고 다시 생성해야 할 수 있습니다.

다음 집계 작업은 먼저 movies 컬렉션 1000보다 큰 runtime 를 가진 영화로 필터링한 다음 _id 및 movie_id 필드에서 comments 컬렉션 과 조인합니다.

db.movies.aggregate( [
{ $match: { runtime: { $gt: 1000 } } },
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "movie_id",
as: "movie_comments"
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
"movie_comments.name": 1,
"movie_comments.text": 1,
"movie_comments.date": 1
}
}
] )
[
{
title: 'Centennial',
year: 1978,
movie_comments: [
{
name: 'Ellaria Sand',
text: 'Excepturi nam nam eum possimus aspernatur autem. Quis nulla optio praesentium ut distinctio explicabo.',
date: ISODate('1995-08-18T03:01:50.000Z')
}
]
},
{ title: 'Baseball', year: 1994, movie_comments: [] }
]

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, movie_comments
FROM movies
WHERE movie_comments IN (
SELECT *
FROM comments
WHERE movie_id = movies._id
);

자세한 내용은 동등성 매치 성능 고려 사항을 참조하세요.

localField가 배열인 경우 $unwind 단계 없이 스칼라 foreignField에 일치시킬 수 있습니다.

다음 집계 작업은 movies 컬렉션 users 컬렉션 과 조인하여 movies 의 cast 배열 필드 users의 스칼라 name 필드 와 일치시킵니다.

db.movies.aggregate( [
{
$match: {
title: {
$in: [ "Roger & Me", "The Sum of Us",
"Centennial" ]
}
}
},
{
$lookup: {
from: "users",
localField: "cast",
foreignField: "name",
as: "cast_users"
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
cast: 1,
"cast_users.name": 1,
"cast_users.email": 1
}
},
{ $sort: { year: 1 } }
] )
[
{
cast: [
'Raymond Burr',
'Barbara Carrera',
'Richard Chamberlain',
'Robert Conrad'
],
title: 'Centennial',
year: 1978,
cast_users: []
},
{
cast: [
'Michael Moore',
'Roger B. Smith',
'Rhonda Britton',
'Fred Ross'
],
title: 'Roger & Me',
year: 1989,
cast_users: [ { name: 'Michael Moore', email: 'michael_moore@fakegmail.com' } ]
},
{
cast: [
'Jack Thompson',
'Russell Crowe',
'John Polson',
'Deborah Kennedy'
],
title: 'The Sum of Us',
year: 1994,
cast_users: [
{
name: 'Deborah Kennedy',
email: 'deborah_kennedy@fakegmail.com'
}
]
}
]

$mergeObjects 연산자는 여러 문서를 단일 문서로 결합합니다.

The following operation uses $lookup to join the movies collection with the comments collection, then uses $mergeObjects in $replaceRoot to merge the first comment document with the movie document:

db.movies.aggregate( [
{ $match: { runtime: { $gt: 1000 } } },
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "movie_id",
as: "movie_comments"
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ $arrayElemAt: [ "$movie_comments", 0 ] },
"$$ROOT"
]
}
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
genres: 1,
name: 1,
email: 1,
text: 1,
date: 1
}
}
] )
[
{
name: 'Ellaria Sand',
email: 'indira_varma@gameofthron.es',
text: 'Excepturi nam nam eum possimus aspernatur autem. Quis nulla optio praesentium ut distinctio explicabo.',
date: ISODate('1995-08-18T03:01:50.000Z'),
genres: [ 'Action', 'Adventure', 'Drama' ],
title: 'Centennial',
year: 1978
},
{
genres: [ 'Documentary', 'History', 'Sport' ],
title: 'Baseball',
year: 1994
}
]

파이프라인은 외부 컬렉션에서 실행할 수 있으며 여러 조인 조건을 포함할 수 있습니다. $expr 연산자를 사용하면 접속사 및 비동등성 매치를 포함한 더 복잡한 조인 조건이 가능합니다.

조인 조건은 aggregate() 메서드가 실행된 로컬 컬렉션의 필드를 참조하고 외부 컬렉션의 필드를 참조할 수 있습니다. 이렇게 하면 두 컬렉션 간에 상관 하위 쿼리가 가능합니다.

MongoDB 5.0은 상관관계가 있는 간결한 하위 쿼리를 지원합니다.

다음 예제입니다.

  • _id 및 movie_id 필드를 사용하여 movies 및 comments 컬렉션을 조인합니다.

  • 영화 출시하다 연도 이후에 게시된 댓글만 포함하도록 댓글을 필터링합니다.

db.movies.aggregate( [
{
$match: {
title: {
$in: [ "Class Action", "Kafka", "Corpse Bride" ]
}
}
},
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "movie_id",
let: { movie_year: "$year" },
pipeline: [
{
$match: {
$expr: {
$gt: [
{ $year: "$date" }, "$$movie_year"
]
}
}
},
{ $project: { _id: 0, name: 1, date: 1 } }
],
as: "post_release_comments"
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
post_release_comments: 1
}
}
] )
[
{
year: 1991,
title: 'Class Action',
post_release_comments: [
{ name: 'Khal Drogo', date: ISODate('2016-12-06T07:17:03.000Z') }
]
},
{
year: 1991,
title: 'Kafka',
post_release_comments: [
{ name: 'Khal Drogo', date: ISODate('1998-05-10T03:10:20.000Z') }
]
},
{ year: 2005, title: 'Corpse Bride', post_release_comments: [] }
]

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, post_release_comments
FROM movies
WHERE post_release_comments IN (
SELECT name, date
FROM comments
WHERE movie_id = movies._id
AND YEAR(date) > movies.year
);

The $eq, $lt, $lte, $gt, and $gte comparison operators placed in an $expr operator can use an index on the from collection referenced in a $lookup stage. Limitations:

  • 인덱스는 필드와 상수 간의 비교에만 사용할 수 있으므로 let 피연산자는 상수로 해결되어야 합니다.

    예를 들어 $a 및 상수 값 간의 비교에는 인덱스를 사용할 수 있지만, $a 및 $b 간의 비교에는 인덱스를 사용할 수 없습니다.

  • let 피연산자가 비어 있거나 누락된 값으로 확인되는 비교에는 인덱스가 사용되지 않습니다.

  • 멀티키, 부분 또는 희소 인덱스는 사용되지 않습니다.

예를 들어 comments 컬렉션에 인덱스 { movie_id: 1 }가 존재하는 경우입니다.

  • comments.movie_id 필드의 동등성 매치는 인덱스를 사용합니다.

An aggregation pipeline $lookup stage can execute a pipeline on the foreign collection, which allows uncorrelated subqueries. An uncorrelated subquery does not reference the local document fields.

참고

Starting in MongoDB 5.0, for an uncorrelated subquery in a $lookup pipeline stage containing a $sample stage, the $sampleRate operator, or the $rand operator, the subquery is always run again if repeated. Previously, depending on the subquery output size, either the subquery output was cached or the subquery was run again.

다음 작업은 movies 컬렉션 에서 런타임이 1000 분보다 긴 영화와 users 컬렉션 조인합니다.

db.users.aggregate( [
{
$match: {
email: { $in: [
"mark_addy@gameofthron.es",
"lena_headey@gameofthron.es"
] }
}
},
{
$lookup: {
from: "movies",
pipeline: [
{ $match: { runtime: { $gt: 1000 } } },
{ $project: { _id: 0, title: 1, year: 1 } }
],
as: "long_movies"
}
},
{
$project: {
_id: 0, name: 1, email: 1, long_movies: 1
}
}
] )
[
{
name: 'Robert Baratheon',
email: 'mark_addy@gameofthron.es',
long_movies: [
{ title: 'Centennial', year: 1978 },
{ title: 'Baseball', year: 1994 }
]
},
{
name: 'Cersei Lannister',
email: 'lena_headey@gameofthron.es',
long_movies: [
{ title: 'Centennial', year: 1978 },
{ title: 'Baseball', year: 1994 }
]
}
]

이 작업은 다음과 같은 유사 SQL 문장에 해당합니다.

SELECT *, long_movies
FROM users
WHERE long_movies IN (
SELECT title, year
FROM movies
WHERE runtime > 1000
);

For more information, see Uncorrelated Subquery Performance Considerations.

버전 5.0의 신규 항목입니다.

Starting in MongoDB 5.0, an aggregation pipeline $lookup stage supports a concise correlated subquery syntax that improves joins between collections. The new concise syntax removes the requirement for an equality match on the foreign and local fields inside of an $expr operator in a $match stage.

다음 예제입니다.

  • Joins the movies and comments collections by matching the localField _id with the foreignField movie_id. The match is performed before the pipeline is run.

  • 댓글을 필터링하여 영화 출시하다 연도 이후에 게시된 댓글만 포함하며, 각각 $$movie_year 및 $date 를 사용하여 액세스합니다.

db.movies.aggregate( [
{
$match: {
title: { $in: [
"I Don't Kiss",
"Lucky Luke",
"Mississippi Masala"
] }
}
},
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "movie_id",
let: { movie_year: "$year" },
pipeline: [
{
$match: {
$expr: {
$gt: [
{ $year: "$date" }, "$$movie_year"
]
}
}
},
{ $project: { _id: 0, name: 1, date: 1 } }
],
as: "post_release_comments"
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
post_release_comments: 1
}
}
] )
[
{
title: "I Don't Kiss",
year: 1991,
post_release_comments: [
{
name: 'Brandon Hardy',
date: ISODate('2016-09-18T11:11:34.000Z')
}
]
},
{
title: 'Lucky Luke',
year: 1991,
post_release_comments: [
{
name: 'Kelsey Smith',
date: ISODate('2010-01-13T17:55:01.000Z')
}
]
},
{
title: 'Mississippi Masala',
year: 1991,
post_release_comments: [
{
name: 'Phillip Collins',
date: ISODate('2010-05-13T08:04:22.000Z')
}
]
}
]

이 예에서는 5.0 이전 버전의 구형 MongoDB 구문을 사용하며 버전에서 앞의 간결한 예와 동일한 결과를 반환합니다.

db.movies.aggregate( [
{
$match: {
title: { $in: [
"I Don't Kiss",
"Lucky Luke",
"Mississippi Masala"
] }
}
},
{
$lookup: {
from: "comments",
let: { movie_id: "$_id", movie_year: "$year" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: [ "$movie_id", "$$movie_id" ] },
{ $gt: [
{ $year: "$date" }, "$$movie_year"
] }
]
}
}
},
{ $project: { _id: 0, name: 1, date: 1 } }
],
as: "post_release_comments"
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
post_release_comments: 1
}
}
] )
[
{
title: "I Don't Kiss",
year: 1991,
post_release_comments: [
{
name: 'Brandon Hardy',
date: ISODate('2016-09-18T11:11:34.000Z')
}
]
},
{
title: 'Lucky Luke',
year: 1991,
post_release_comments: [
{
name: 'Kelsey Smith',
date: ISODate('2010-01-13T17:55:01.000Z')
}
]
},
{
title: 'Mississippi Masala',
year: 1991,
post_release_comments: [
{
name: 'Phillip Collins',
date: ISODate('2010-05-13T08:04:22.000Z')
}
]
}
]

이전 예시는 다음 유사 SQL 문에 해당합니다.

SELECT *, post_release_comments
FROM movies
WHERE post_release_comments IN (
SELECT *
FROM comments
WHERE comments.movie_id = movies._id
AND YEAR(comments.date) > movies.year
);

For more information, see Correlated Subquery Performance Considerations.