Search code examples
mongodbcollectionslimitlookup

MongoDB $lookup creates array


So I am trying to join two collections together:

Collections are:

  1. shows
  2. episodes

I am using the $lookup value inside the shows collection.

[{$lookup: {
  from: 'episode',
  localField: 'url',
  foreignField: 'show_b',
  as: 'match_docs'
}}]

However I am getting all of the episodes from each show inside the match_docs in theory that is fine, however I need to be able to limit it to the latest episode limit:1 for each show ordered by pubDate

If anyone knows how I could limit the match_docs to only lookup once that would be great

I have also tried

{
  from: 'episode',
  localField: 'url',
  foreignField: 'show_b',
  pipeline: [
              {$sort:{id:1}},{$limit:1},
              ],
  as: 'match_docs'
}

With no success.


Solution

  • That would be easy with the second syntax of $lookup:

    [
        {
            $lookup: {
                from: 'episodes', # make sure your collection name is correct
                let: {url: '$url'},
                pipeline: [
                    {
                        $match: {
                            $expr: {
                                $eq: ['$show_b', '$$url']
                            }
                        }
                    },
                    {
                         $sort: {
                            pubDate: -1
                        }
                    },
                    {
                        $limit: 1
                    } 
                ],
                as: 'match_docs'
            }
        }
    ]