1

I'm having the following document structure:

{
  _id: 123,
  name: 'My playlist',
  videos:[
   {videoId:1},
   {videoId:2},
   {videoId:3}]
}

Now I want to do a $lookup in the video collection to get all video data. At the end, I need a data structure like this:

{
  _id: 123,
  name: 'My playlist',
  videos:[
   {videoId:1, videoDetails:[{_id:1, title:'My funny video', views:123}]},
   {videoId:2, videoDetails:[{_id:2, title:'My new video', views:1234}]},
   {videoId:3, videoDetails:[{_id:3, title:'Another video', views:1236}]}]
}

Is this possible with MongoDB 3.2 and the $lookup aggregate?

user2891491
  • 351
  • 8
  • 16
  • Nope, there is no example on https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ for this. I need to assign the "as" parameter so each single object. They assign it to the main document. – user2891491 Sep 28 '16 at 23:21

1 Answers1

6

You can do it with something like this in MongoDB 3.2 assuming the collection that has the details is video.details and the field you are left-joining on is _id:

[  
   {  
      $unwind:"$videos"
   },
   {  
      $lookup:{  
         from:"video.details",
         localField:"videos.videoId",
         foreignField:"_id",
         as:"details"
      }
   },
   {  
      $group:{  
         _id:"$_id",
         name:{  
            $first:"$name"
         },
         videos:{  
            $push:{  
               videoId:"$videos.videoId",
               videoDetails:"$details"
            }
         }
      }
   }
]

So basically you do your lookup but later in a $group stage build the output the way you like it. you may not need the first $unwind stage if you are using MongoDB 3.3.4 or above (previous to that $lookup on arrays weren't allowed).

Amin J
  • 1,179
  • 9
  • 16