Wie kann ich die Eigenschaften einer anderen Sammlung in einem Sub-Array aufrufen?
Nov 26 2020
Ich habe 2 Sammlungen: eine namens places
und type_places
. a place
hat einen Typ von place ( type_places
) zugeordnet, und dies kann einige Objekte von diesem ( objects
Array) zugeordnet haben.
type_places
{
"_id": "5fbc7cc705253c2da482023f",
"type_place": "office",
"objects": [
{
"_id": "5fbc7cc705253c2da48202saw",
"name": "chair"
},
{
"_id": "5fbc7cc705253c2da4820242",
"name": "table"
},
{
"_id": "5fbc7cc705253c2da482025f",
"name": "desktop"
}
]
}
places
{
"_id": "5fbc7cc705253c2da482025f",
"place": "Room 5",
"type_place_id": "5fbc7cc705253c2da482023f", /*"office"*/
"type_place_objects": [
{
"_id": "5fbc7cc705253c2da48202saw", /*chair*/
"quantify": 4
},
{
"_id": "5fbc7cc705253c2da482025f", /*desktop*/
"quantify": 2
}
]
}
dann möchte ich, dass wenn ich a abfrage place
, die Abfrage mir zeigt, place
dass ich konsultiert werde, welche Art von Ort es ist ( type_place
) und welche objects
Art von Ort es hat
Ausgabe gewünscht:
{
"_id": "5fbc7cc705253c2da482023f",
"place": "Room 5",
"type_place_objects": [
{
"_id": "5fbc7cc705253c2da48202saw",
"name": "chair",
"quantify": 4
},
{
"_id": "5fbc7cc705253c2da482025f",
"name": "desktop",
"quantify": 2
}
]
}
Ich versuche das, aber es funktioniert nicht:
place.aggregate(
[
{
"$match": {"place":"Room 5"} }, { "$lookup": {
"from": "type_place",
"localField": "type_place_id",
"foreignField": "_id",
"as": "type_place_objects"
}
},
{
"$sort": { "_id": -1 } }, { "$project": {
"_id":1,
"place":1,
"type_place_objects": 1
}
}
])
Wie kann man das beheben?
Antworten
1 varman Nov 27 2020 at 07:55
Es kann viele Möglichkeiten geben, eine Möglichkeit ist die Verwendung, $lookup
wie Sie es bereits versucht haben
db.place.aggregate([
{ "$match": { "place": "Room 5" } },
{ $unwind: "$type_place_objects" },
{
"$lookup": { "from": "type_place", "let": { tpo: "$type_place_objects._id" },
"pipeline": [
{ $unwind: "$objects" },
{
$match: { $expr: {
$eq: [ "$objects._id", "$$tpo" ] } } } ], "as": "join" } }, { $addFields: {
"join": { "$arrayElemAt": [ "$join", 0]
}
}
},
{
$addFields: { "type_place_objects.name": "$join.objects.name" }
},
{
$group: { _id: "$_id",
place: { $first: "$place" },
type_place_objects: { "$addToSet": "$type_place_objects" }
}
}
])
Arbeitender Mongo-Spielplatz