0

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?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
mmu36478
  • 1,295
  • 4
  • 19
  • 40
  • You **still** need to `$unwind` the array if it contains an "object" rather than a "flat" list of values. MongoDB 3.4 fixed the "flat" values without `$unwind`, but this case remains the same. You are trying to build a "hierarchy" using `$lookup`. Don't do that. You cannot recurse ( no doubt your next question ) and there are better ways to create a tree in post processing as well as better ways to search without making a tree. – Neil Lunn May 30 '17 at 07:15
  • But in the question that you link to it creates another object. I wanted to add as a field in children array. Maybe you're right, I have to think better solutions. – mmu36478 May 30 '17 at 07:38
  • The question I link to explains the solution to the "result" you are seeing. My further comments deal with your "intentions". You cannot recurse through the results. – Neil Lunn May 30 '17 at 07:41

0 Answers0