Assume I have database structure as;
[
{id:1, name: "alex", children: [ {id: 2}, {id: 5}]},
{id:2, name: "felix", children: []},
{id:5, name: "tom", children: [{id: 6}]},
{id:6, name: "hannah", children: []}
]
I want to add name field to the children array where id's are matched.What I'm trying to say is, I want to write a query which returns as;
[
{id:1, name: "alex", children: [ {id: 2, name: "felix"}, {id: 5, name: "tom"}]},
{id:2, name: "felix", children: []},
{id:5, name: "tom", children: [{id: 6, name: hannah}]},
{id:6, name: "hannah", children: []}
]
To able to do this. Firstly, I think about getting the matching records as;
db.collection.aggregate([
{$lookup: {from: "collection", localField: "children.id", foreignField: "id" , as: "array"}},
])
But array
returns as empty. I couldn't go further.
How can I modify the query? Where should I start from?