B와 함께 외국인이있는 컬렉션 A, 컬렉션 C를 가진 외국인이있는 컬렉션, A에서 컬렉션 C로 외국인을 데려 오려면 어떻게해야하나요? (집계)

Nov 28 2020

3 개의 컬렉션이 있습니다.

    country
    {
        "_id": "5fbc7cc705253c2da4820425",
        "country":"USA"
    }

    city
    {
        "_id": "5fbc7cc705253c2da482025f",
        "city": "New York",
        "country_id":"5fbc7cc705253c2da4820425",
    }

    travel_reservation
    {
        "_id":"5fbc7cc705253c2da48202yQ"
        "name_person":"pablo rojas",
        "city_id":"5fbc7cc705253c2da482025f"
    }

country수집하는 city수집과 여행 예약 컬렉션 ( travel_booking). 그런 다음 여행 예약 컬렉션 ( travel_booking)에서 사람은 관련 도시 ( city_id)를 가지고 있습니다.

나는 총 수익의 이름을 얻는 외에 다음 하나? 같은 구조를 만들 수있는 방법 city, 나는 또한의 이름을 얻을 수 있습니다 country.

원하는 출력 :

    {
        "_id":"5fbc7cc705253c2da48202yQ",
        "name_person":"pablo rojas",
        "city":{
            "_id":"5fbc7cc705253c2da482025f",
            "city":"New York"
        },
        "country":{
            "_id":"5fbc7cc705253c2da4820425",
            "country":"USA"
        }
    }

나는 이것을 시도했다 :

https://mongoplayground.net/p/JVhroCubElX

답변

1 turivishal Nov 28 2020 at 17:41
  • $lookup 시 컬렉션 가입
  • $lookup 국가 컬렉션에 가입
  • $project에서 첫 번째 요소를 얻을 필수 필드를 표시합니다 citycountry사용$first
db.travel_reservation.aggregate([
  {
    $lookup: { from: "city", localField: "city_id", foreignField: "_id", as: "city" } }, { $lookup: {
      from: "country",
      localField: "city.country_id",
      foreignField: "_id",
      as: "country"
    }
  },
  {
    $project: { name_person: 1, city: { $first: "$city" }, country: { $first: "$country" }
    }
  }
])

운동장