我在 MongoDB 集合中有如下資料。
{ "_id" : 1, "name" : "Dev" }
{ "_id" : 2, "name" : "Eliot", "parentId" : 1 }
{ "_id" : 3, "name" : "Ron", "parentId" : 2 }
{ "_id" : 4, "name" : "Andrew", "parentId" : 2 }
{ "_id" : 5, "name" : "Asya", "parentId" : 3 }
{ "_id" : 6, "name" : "Dan", "parentId" : 4 }
我可以使用“$graphLookup”來獲取孩子和父母。
db.xmantree.aggregate( [
{
name: "Eliot"
},
{
$graphLookup: {
from: 'xmantree',
startWith: '$_id',
connectFromField: 'parentId',
connectToField: 'parentId',
as: 'children'
}
},
{
$graphLookup: {
from: 'xmantree',
startWith: '$parentId',
connectFromField: 'parentId',
connectToField: '_id',
as: 'parents'
}
}
] )
結果是這樣的。
{
_id:2,
name: "Eliot",
parentId: 1,
children: [
{
_id: 3,
name: "Ron",
parentId: 2,
},
{
_id: 4,
name: "Andrew",
parentId: 2,
},
],
parents: [
{
_id: 1,
name: "Dev"
}
]
}
但在這種情況下,羅恩和安德魯每個人都有更多的孩子。所以我想通過一個聚合查詢遞回地得到這個。
比如這種結果。
{
_id:2,
name: "Eliot",
parentId: 1,
children: [
{
_id: 3,
name: "Ron",
parentId: 2,
children: [...] // <- I want to get this.
},
{
_id: 4,
name: "Andrew",
parentId: 2,
children: [...] // <- I want to get this.
},
],
parents: [
{
_id: 1,
name: "Dev"
}
]
}
我的目標在 MongoDB 中可能實作嗎?
uj5u.com熱心網友回復:
您可以$graphLookup像這樣設定以獲取所有子節點的陣列:
{
$graphLookup: {
from: "xmantree",
startWith: "$_id",
connectFromField: "_id",
connectToField: "parentId",
as: "children"
}
}
這是Mongo 游樂場供您參考。
但是,對于預期的分層輸出形式,您需要知道遞回級別。如果您有這些資訊,您可以執行以下操作:
db.xmantree.aggregate([
{
"$match": {
name: "Eliot"
}
},
{
"$lookup": {
"from": "xmantree",
let: {
parentId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$parentId",
"$parentId"
]
}
}
},
{
"$lookup": {
"from": "xmantree",
"localField": "_id",
"foreignField": "parentId",
"as": "children"
}
}
],
"as": "children"
}
}
])
這是Mongo 游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357795.html
標籤:MongoDB
上一篇:如何在MongoDB中的2個不同集合(帶分頁)中進行搜索
下一篇:使用MongoDB對檔案進行分組
