コレクションAにBの外国人がいる、Bにコレクション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
必須フィールドを表示するには、最初の要素を取得しcity
てcountry
使用します$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" }
}
}
])
遊び場