私は2つのコレクションを持っています:1つはとplaces
と呼ばれtype_places
ます。aplace
は場所のタイプ(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つの方法は$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" }
}
}
])
働くモンゴの遊び場
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加