我在兩個 MongoDB 集合中有如下資料。類別:
[
{ "_id" : 1, "name" : "A" },
{ "_id" : 2, "name" : "B", "categoryId" : 1 },
{ "_id" : 3, "name" : "C", "categoryId" : 1 },
{ "_id" : 4, "name" : "D", "categoryId" : 2 },
{ "_id" : 5, "name" : "E", "categoryId" : 3 },
{ "_id" : 6, "name" : "F", "categoryId" : 2 }
];
我有Locos檔案:
[
{ "_id" : 1, "name" : "X", "categoryId" : 2 },
{ "_id" : 2, "name" : "Y", "categoryId" : 3 },
{ "_id" : 2, "name" : "B", "categoryId" : 1 }
]
例如,如果我想獲取所有具有 id 1的類別A的孩子,我呼叫該函式,它回傳一個孩子類別的 id 陣列,如果可能的話,回傳 Locos 孩子。所以結果會是這樣的:
chilren: {
categories: [2, 3, 4, 5, 6],
locos: [1, 2, 3]
}
如果我使用 id 2即類別B呼叫函式,我會得到結果:
chilren: {
categories: [2, 6],
locos: [1]
}
uj5u.com熱心網友回復:
您在正確的軌道上使用$graphLookup.
db.categories.aggregate([
{
"$match": {
_id: 1
}
},
{
"$graphLookup": {
"from": "categories",
"startWith": "$_id",
"connectFromField": "_id",
"connectToField": "categoryId",
"as": "categoryLookup"
}
},
{
"$graphLookup": {
"from": "locos",
"startWith": "$_id",
"connectFromField": "_id",
"connectToField": "categoryId",
"as": "locosLookup"
}
},
{
"$project": {
children: {
categories: {
"$map": {
"input": "$categoryLookup",
"as": "c",
"in": "$$c._id"
}
},
locos: {
"$map": {
"input": "$locosLookup",
"as": "l",
"in": "$$l._id"
}
}
}
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406704.html
標籤:
