0

I have two collections. The first one's documents have the following structure:

{
    _id: "some ObjectId"
    data: [ 1, 2 ,3 ]
}

The second one's documents have the following structure:

{
    _id: "some object id",
    value: 1,
    name: "first",
}

I want to get document from first collection and add to each item of its data array field name from the second collection. Result I want to get looks like

{
    _id: "some ObjectId"
    data: [ 
       { id: 1, name: "first"}, 
       { id: 2, name: "first"},
       { id: 3, name: "first"}
   ]
}

where "first", "second" and "third" are values of field name from second collection's items. As I know I should use aggregate and lookup but I don't know how to do it prperly. How do I get this result?

UPD. This question is not duplicate. I know how to use $lookup but I don't know how to use it with array items!

Pupkin
  • 1,211
  • 3
  • 13
  • 30
  • 2
    Still a duplicate since starting with MongoDB 3.4, if the localField is an array, you can match the array elements against a scalar foreignField without needing an $unwind stage, hence you can still use $lookup on the array – chridam Aug 30 '19 at 16:39
  • 2
    Also FYI, adding content like "not a duplicate" and even "I know how to use" does not really carry any weight with people unless you can specifically show an example listing which does not work as expected. At the very least, including such code *will* most likely get at least a comment response pointing out how to correct the error in the code, and thus get your solution. Always show what you actually did in a question instead of simply saying "does not work". – Neil Lunn Aug 31 '19 at 00:21

0 Answers0