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"
}
}
])
查詢只返回第一級父。你有什麼建議嗎?
是否可以重構數據?而且,數據的更改頻率如何?看看這個:https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-ancestors-array/和https://docs.mongodb.com/manual/tutorial/model-tree-structures -with-materialized-paths/ –
不,但謝謝你的鏈接!你給我靈感來解決這個問題 –