該結構或多或少像;
[
{id: 1, name: "alex" , children: [2, 4, 5]},
{id: 2, name: "felix", children: []},
{id: 3, name: "kelly", children: []},
{id: 4, name: "hannah", children: []},
{id: 5, name: "sonny", children: [6]},
{id: 6, name: "vincenzo", children: []}
]
我想的名字來代替children
ID的時候children
數組不爲空。
所以查詢的結果是預期的;
[ {id: 1, name: "alex" , children: ["felix", "hannah" , "sonny"]}
{id: 5, name: "sonny", children: ["vincenzo"]}
]
我做了什麼來實現這一點;
db.list.aggregate([
{$lookup: { from: "list", localField: "id", foreignField: "children", as: "children" }},
{$project: {"_id" : 0, "name" : 1, "children.name" : 1}},
])
充滿兒童與其父,這不是我想要的:)
{ "name" : "alex", "parent" : [ ] }
{ "name" : "felix", "parent" : [ { "name" : "alex" } ] }
{ "name" : "kelly", "parent" : [ ] }
{ "name" : "hannah", "parent" : [ { "name" : "alex" } ] }
{ "name" : "sonny", "parent" : [ { "name" : "alex" } ] }
{ "name" : "vincenzo", "parent" : [ { "name" : "sonny" } ] }
我是怎麼誤解?
謝謝你的回答。我瞭解我對localField和ForeignField的錯誤。但是你能解釋查詢中的$ group嗎? – mmu36478
因爲'$ unwind' * children *數組使它爲每個* children *分開文檔,然後再使它成爲* children的數組*需要使用'$ group'。可以看到https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/#unwind-array –
就像你在每個聚合方法之後顯示當前狀態一樣 - 使得它更容易遵循。 +1 –