本文介绍了集合 A 有一个外国人和 B,B 有一个外国人和集合 C,我如何将外国人从 A 带到集合 C?(汇总)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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).

a country collection, a city collection and a travel booking collection(travel_booking).then in the travel booking collection (travel_booking) a person has an associated city (city_id).

如何让聚合返回如下结构?,其中除了获取city的名称外,还可以获取country的名称代码>.

How can I make an aggregate return a structure like the following one?, where in addition to obtaining the name of the city, I can also obtain the name of the country.

所需的输出:

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

我已经试过了:

https://mongoplayground.net/p/JVhroCubElX

推荐答案

  • $lookup 加入城市收藏
  • $lookup 加入国家集合
  • $project 显示必填字段,使用 $firstcitycountry 获取第一个元素立>

    • $lookup join city collection
    • $lookup join country collection
    • $project to show required fields, get first element from city and country using $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" }
          }
        }
      ])
      

      游乐场

      这篇关于集合 A 有一个外国人和 B,B 有一个外国人和集合 C,我如何将外国人从 A 带到集合 C?(汇总)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 05:14