

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# \$1lookup
<a name="lookup"></a>

Amazon DocumentDB의 `$lookup` 집계 단계를 사용하면 두 컬렉션 간에 왼쪽 외부 조인을 수행할 수 있습니다. 이 작업을 사용하면 일치하는 필드 값을 기반으로 여러 컬렉션의 데이터를 결합할 수 있습니다. 관련 컬렉션의 데이터를 쿼리 결과에 통합해야 할 때 특히 유용합니다.

**파라미터**
+ `from`: 조인을 수행할 컬렉션의 이름입니다.
+ `localField`:와 일치시킬 입력 문서의 필드입니다`foreignField`.
+ `foreignField`: `from` 컬렉션에 있는 문서의 필드로,와 일치합니다`localField`.
+ `as`: `from` 컬렉션의 일치하는 문서가 포함된 출력 문서에 추가할 새 필드의 이름입니다.

## 예제(MongoDB 쉘)
<a name="lookup-examples"></a>

다음 예제에서는 `orders` 컬렉션의 데이터를 `customers` 컬렉션에 조인하는 간단한 `$lookup` 작업을 보여줍니다.

**샘플 문서 생성**

```
db.customers.insertMany([
  { _id: 1, name: "Alice" },
  { _id: 2, name: "Bob" },
  { _id: 3, name: "Charlie" }
]);

db.orders.insertMany([
  { _id: 1, customer_id: 1, total: 50 },
  { _id: 2, customer_id: 1, total: 100 },
  { _id: 3, customer_id: 2, total: 75 }
]);
```

**쿼리 예제**

```
db.customers.aggregate([
  {
    $lookup: {
      from: "orders",           
      localField: "_id",        
      foreignField: "customer_id", 
      as: "orders" 
    }
  }
]);
```

**출력**

```
[
  {
    _id: 1,
    name: 'Alice',
    orders: [
      { _id: 2, customer_id: 1, total: 100 },
      { _id: 1, customer_id: 1, total: 50 }
    ]
  },
  { _id: 3, name: 'Charlie', orders: [] },
  {
    _id: 2,
    name: 'Bob',
    orders: [ { _id: 3, customer_id: 2, total: 75 } ]
  }
]
```

## 코드 예제
<a name="lookup-code"></a>

`$lookup` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  await client.connect();

  const db = client.db('test');

  const result = await db.collection('customers').aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer_id',
        as: 'orders'
      }
    }
  ]).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    db = client.test
    
    collection = db.customers

    pipeline = [
        {
            "$lookup": {
                "from": "orders",
                "localField": "_id",
                "foreignField": "customer_id",
                "as": "orders"
            }
        }
    ]

    result = collection.aggregate(pipeline)

    for doc in result:
        print(doc)

    client.close()

example()
```

------