我需要將來自同一個表“物體”的物體連接在一起。本地鍵是本地物體的_id。外鍵位于物件的“rels”陣列中(_id 存盤在 rels.r 中)。
當我使用示例 _id 字串測驗 $match 時,查找作業正常。但是當我嘗試使用用 'let' 宣告的變數時(它應該使用相同的字串,只是在一個變數中)它不起作用。
示例資料:
{ // PARENT ENTITY
"_id":"123", // the local key
"title":"initialentity",
},
{ // CHILD ENTITY
"_id":"456",
"title":"relatedentity",
"rels":[
{
"r":"123", // the foreign key
"a":"exampledata-ignorethisfield",
},
]
}
聚合:
[
{ "$lookup": {
"from": "entities",
"let": { "id": { $toString: "$_id" } },
// "let": { "id": "$_id" }, // this alternative let doesn't work either
"pipeline": [
//{ "$match": { "rels.r": "123" } }, // This test works fine
{ "$match": { "rels.r": "$$id" } }, // But this, using the let variable, doesn't work
{"$limit": 1}
],
"as": "result"
}},
{"$limit": 1}
]
實際輸出(結果陣列為空):
{
"_id":"123", // the local key
"title":"initialentity",
"results": []
},
預期輸出(結果陣列具有相關物件):
{
"_id":"123", // the local key
"title":"initialentity",
"results": [
{
"_id":"456",
"title":"relatedentity",
"rels":[
{
"r":"123", // the foreign key
"a":"exampledata-ignorethisfield",
},
]
}
]
},
由于將添加其他條件,我需要它使用此方法(帶管道)。
在此先感謝您的幫助。我確定我遺漏了一些明顯的東西。我已經瀏覽了許多 SO qs 和 mongo 檔案,但無法弄清楚這一點。我也嘗試過類似以下的事情但沒有成功:
{ "$match": { $expr: { "rels": {"r" : "$$id"} } } }, // This doesn't work (returns unrelated entities)
{ "$match": { $expr: { $eq: [ "rels.r" , "$$id" ] } } }, // This doesn't work (returns empty array)
uj5u.com熱心網友回復:
您需要使用$expr您已經按順序嘗試訪問該變數 $$id,但你也需要前綴rels.r以$使其在值進行比較rels.r來$$id,而不是文本字串"rels.r"。
[
{ "$lookup": {
"from": "entities",
"let": { "id": { $toString: "$_id" } },
"pipeline": [
{ "$match": { $expr: { $eq: [ "$rels.r" , "$$id" ] } } },
{ "$limit": 1 }
],
"as": "result"
}},
{ "$limit": 1 }
]
編輯
$eq如果您與一組物件匹配,則似乎不起作用,我已經能夠使用$in以下方法使其作業:
[
{ "$lookup": {
"from": "entities",
"let": { "id": { $toString: "$_id" } },
"pipeline": [
{ "$match": { $expr: { $in: [ "$$id" , { $ifNull: [ "$rels.r", [] ] } ] } } },
{ "$limit": 1 }
],
"as": "result"
}},
{ "$limit": 1 }
]
我選擇包含$ifNull是因為$in如果第二個引數沒有決議為陣列,則會失敗,如果檔案沒有rels欄位,則會發生這種情況。如果每個檔案確實有一個rels場,隨時有利于只是省略此"$rels.r"。
作業 MongoPlayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/392582.html
上一篇:如何維護資料庫中的排序串列?
