0

I would like to map back the valuse from a $lookup operation to local array field.

Currently, I am only able to create a standalone array field using $lookup, but not able to map the value back inside the original array.

An example of document:

Input

User: 
{
  "_id": "58a4fa0e24180825b05e14e9"
  "events": [
    {"eventId": "100", "joined": ISODate("2019-10-04T04:25:44.636Z")}, 
    {"eventId": "1001", "joined": ISODate("2019-10-04T04:25:44.636Z")}, 
    {"eventId": "1002", "joined": ISODate("2019-10-04T04:25:44.636Z")}
}

Event: 
{
  "eventId": "100",
  "eventName": "Taco Day"
}

Output I want:

User:
{
  "_id": "58a4fa0e24180825b05e14e9"
  "events": [
    {"eventId": "100", "joined": ISODate("2019-10-04T04:25:44.636Z"), eventName: "Taco Day"}, 
    {"eventId": "1001", "joined": ISODate("2019-10-04T04:25:44.636Z")}, 
    {"eventId": "1002", "joined": ISODate("2019-10-04T04:25:44.636Z")}
}
chakwok
  • 980
  • 8
  • 21
  • 1
    Try https://mongoplayground.net/p/2D2_TNtfIVB – sushant mehta Oct 04 '19 at 06:32
  • @sushantmehta That works! I see that you used the `$filter` inside a `$map`. What if I know that for each eventId in `User.events`, there must be a coresponding event in `Event` collection. Is there a way I can optimize the query? – chakwok Oct 08 '19 at 03:36
  • There's no `$$index` variable inside `$map`. I am not able to eliminate the nested operation... – chakwok Oct 08 '19 at 04:33

0 Answers0