Sammlung A, die einen Ausländer mit B hat, B hat einen Ausländer mit Sammlung C, wie kann ich einen Ausländer von A zur Sammlung C bringen? (Aggregat)
Nov 28 2020
Ich habe 3 Sammlungen:
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"
}
eine country
Sammlung, eine city
Sammlung und eine Reisebuchungssammlung ( travel_booking
). dann travel_booking
hat eine Person in der Reisebuchungssammlung ( ) eine zugeordnete Stadt ( city_id
).
Wie kann ich ein Aggregat dazu bringen, eine Struktur wie die folgende zurückzugeben? Dabei kann ich neben dem Namen des city
auch den Namen des erhalten country
.
Ausgabe gewünscht:
{
"_id":"5fbc7cc705253c2da48202yQ",
"name_person":"pablo rojas",
"city":{
"_id":"5fbc7cc705253c2da482025f",
"city":"New York"
},
"country":{
"_id":"5fbc7cc705253c2da4820425",
"country":"USA"
}
}
Ich habe das versucht:
https://mongoplayground.net/p/JVhroCubElX
Antworten
1 turivishal Nov 28 2020 at 17:41
$lookup
Tritt der Stadtsammlung bei$lookup
Ländersammlung beitreten$project
Um die erforderlichen Felder anzuzeigen, rufen Sie das erste Element abcity
undcountry
verwenden es$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" }
}
}
])
Spielplatz