2017-09-20 71 views
0

我有一個位置集合,並希望檢索頂級父級位置。 例如,如果我通過id 4查詢位置,應該返回id爲1的位置。MongoDB遞歸查詢頂級父對象

{_id: "1", "parentLocationID": null, "childLocationIds": [2]} 
{_id: "2", "parentLocationID": "1", "childLocationIds": [3]} 
{_id: "3", "parentLocationID": "2", "childLocationIds": [4]} 
{_id: "4", "parentLocationID": "3", "childLocationIds": []} 

我目前的解決辦法是遞歸查詢從後端數據庫,直到parentLocationID爲空。 我想要做的是將遞歸處理移動到Mongo。 我發現,蒙戈支持遞歸查詢與$graphLookup,這就是我如何開始的:

db.locations.aggregate([ 
    { 
     "$match": { 
      "childLocationIds": {"$elemMatch": {"$eq", "4"}} 
     } 
    }, 
    { 
     "$graphLookup": { 
      "from": "locations", 
      "startWith: "$childLocationIds", 
      "connectFromField": "childLocationIds", 
      "connectToField": "childLocationIds", 
      "as": "parentLocations" 
     } 
    } 
]) 

查詢只返回第一級父。你有什麼建議嗎?

+0

是否可以重構數據?而且,數據的更改頻率如何?看看這個:https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-ancestors-array/和https://docs.mongodb.com/manual/tutorial/model-tree-structures -with-materialized-paths/ –

+0

不,但謝謝你的鏈接!你給我靈感來解決這個問題 –

回答

1

找到了解決辦法,需要一對夫婦更管道:

db.locations.aggregate([ 
    { 
     "$match": { 
      "_id": "4" 
     } 
    }, 
    { 
     "$graphLookup": { 
      "from": "locations", 
      "startWith: "$parentLocationID", 
      "connectFromField": "_id", 
      "connectToField": "parentLocationID", 
      "as": "parentLocations" 
     } 
    }, 
    { 
     "$unwind": "$parentLocations" 
    }, 
    { 
     "$replaceRoot": { 
      "newRoot": "$parentLocations" 
     } 
    }, 
    { 
     "$match": { 
      "parentLocationID": null 
     } 
    } 
]) 

$匹配將ID 4找到位置,然後$ graphLookup將父對象追加到parentLocations財產。剩餘的管道用於提取頂層位置。