하위 배열의 다른 컬렉션에있는 속성을 어떻게 호출 할 수 있습니까?
Nov 26 2020
나는이 컬렉션이 있습니다 전화를 places
하고 type_places
. a place
는 장소 유형 ( type_places
)과 연관되어 있으며 this ( objects
배열)의 일부 객체와 연관 될 수 있습니다 .
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
}
]
}
나는 내가 쿼리 할 때 것을 원하는 place
쿼리 나 쇼 place
, 어떤 장소의 그것이 제가 상담을하고 있다는 점이다 ( type_place
) 어떤 objects
장소의 유형을가있다
원하는 출력 :
{
"_id": "5fbc7cc705253c2da482023f",
"place": "Room 5",
"type_place_objects": [
{
"_id": "5fbc7cc705253c2da48202saw",
"name": "chair",
"quantify": 4
},
{
"_id": "5fbc7cc705253c2da482025f",
"name": "desktop",
"quantify": 2
}
]
}
나는 이것을 시도하고 있지만 작동하지 않습니다.
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
}
}
])
어떻게 고칠 수 있습니까?
답변
1 varman Nov 27 2020 at 07:55
여러 가지 방법이있을 수 있습니다. 한 가지 방법은 $lookup
이미 시도한대로 사용 하는 것입니다.
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" }
}
}
])
일하는 몽고 놀이터