다음을 통해 공유


$lookup(집계)

적용 대상: MongoDB vCore

$lookup 집계 프레임워크의 단계는 다른 컬렉션과 왼쪽 외부 조인을 수행하는 데 사용됩니다. 지정된 조건에 따라 여러 컬렉션의 문서를 결합할 수 있습니다. 이 연산자는 여러 쿼리를 수행할 필요 없이 다른 컬렉션의 관련 데이터를 사용하여 문서를 보강하는 데 유용합니다.

구문

단계의 구문 $lookup 은 다음과 같습니다.

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

매개 변수

설명
from 조인할 컬렉션의 이름입니다.
localField 와 일치하는 foreignField입력 문서의 필드입니다.
foreignField 컬렉션에 있는 문서의 필드로, from 이 필드와 localField일치합니다.
as 입력 문서에 추가할 새 배열 필드의 이름입니다. 이 배열에는 컬렉션의 일치하는 문서가 포함됩니다 from .

예시

두 개의 문서가 있는 컬렉션이 ratings 있다고 가정해 보겠습니다.

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "rating": 5
}
{
  "_id": "fecca713-35b6-44fb-898d-85232c62db2f",
  "rating": 3
}

매장 컬렉션에서 다음 샘플 json을 사용하여 사용량을 이해해 보겠습니다.

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
   "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": {
    "lat": 60.1441,
    "lon": -141.5012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 2,
      "partTime": 0
    }
  },
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "DJ Headphones",
        "totalSales": 35921
      }
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Bargain Blitz Days",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 3,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 2,
          "Day": 18
        }
      },
      "discounts": [
        {
          "categoryName": "DJ Turntables",
          "discountPercentage": 18
        },
        {
          "categoryName": "DJ Mixers",
          "discountPercentage": 15
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

컬렉션과 ratings 컬렉션을 조인하여 5등급을 stores 가진 각 저장소와 관련된 프로모션 이벤트를 나열하려고 합니다.

db.ratings.aggregate([
  // filter based on rating in ratings collection
  {
    $match: {
      "rating": 5
    }
  },
  // find related documents in stores collection
  {
    $lookup: {
      from: "stores",
      localField: "_id",
      foreignField: "_id",
      as: "storeEvents"
    }
  },
  // deconstruct array to output a document for each element of the array
  {
    $unwind: "$storeEvents"
  },
   // Include only _id and name fields in the output 
  { $project: { _id: 1, "storeEvents.name": 1 } }  

])

이 쿼리는 다음 문서를 반환합니다.

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "storeEvents": { "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile" }
  }
]

제한 사항

  • let은 파이프라인의 일부로 지원되지 않습니다.