la collection A qui a un étranger avec B, B a un étranger avec la collection C, comment puis-je amener un étranger de A à la collection C? (Agrégat)

Nov 28 2020

J'ai 3 collections:

    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"
    }

une countrycollection, une citycollection et une collection de réservation de voyage ( travel_booking). puis dans la collection de réservation de voyage ( travel_booking), une personne a une ville associée ( city_id).

Comment puis-je faire en sorte qu'un agrégat renvoie une structure comme la suivante ?, Où en plus d'obtenir le nom du city, je peux également obtenir le nom du country.

Sortie souhaitée:

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

J'ai essayé ceci:

https://mongoplayground.net/p/JVhroCubElX

Réponses

1 turivishal Nov 28 2020 at 17:41
  • $lookup rejoindre la collection de la ville
  • $lookup rejoindre la collection de pays
  • $projectpour afficher les champs obligatoires, obtenir le premier élément de cityet en countryutilisant$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" }
    }
  }
])

Terrain de jeux