[英]Mongodb query all records inheriting parent `_id` down the stack
我在一個集合中有以下數據結構,其中N
個條目繼承了 _id 作為parent_id
。
測驗:如果我有 top _id "_id": "56ce2713"
我如何查詢所有 parent_id 的 parent_id 的 parent_id 無限。
{
"_id" : "56ce2713",
"name" : "one",
"parent_id":null
"insertedAt" : ISODate("2021-05-04T12:48:38.067Z"),
}
{
"_id" : "d0e6054e9795",
"name" : "Two",
"parent_id": "56ce2713"
"insertedAt" : ISODate("2021-05-04T12:48:38.067Z"),
}
...............
{
"_id" : "6169-44a2",
"name" : "N",
"parent_id": "d0e6054e9795"
"insertedAt" : ISODate("2021-05-04T12:48:38.067Z"),
}
您可以使用$graphLookup ,對集合執行遞歸搜索,並提供通過遞歸深度和查詢過濾器限制搜索的選項,
$match
你的條件$graphLookup
傳遞_id
作為startWith
和connectFromFields
,傳遞parent_id
作為connectToField
db.collection.aggregate([
{ $match: { _id: "56ce2713" } },
{
$graphLookup: {
from: "collection",
startWith: "$_id",
connectFromField: "_id",
connectToField: "parent_id",
as: "children"
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.