Lookup performance with limit: 1

Hi I came across with this discussion where it was advised to limit the lookup only to the first occurrence.
It got me wondering if I have a lookup with a limit set to one:

      $lookup: {
        from: collection_name,
        let: { idToSearchFor: '$_id' },
        pipeline: [
            $match: {
              $expr: {
                $and: [
                  { $eq: ['$$idToSearchFor', '$another_id'] },
                  { $eq: ['dummy', '$another_field'] },
          { $limit: 1 },
        as: 'nice_name',

Is Mongo clever enough to terminate after the first match, or still will search through the whole collection, collecting all the matches and then returning with the very first one?

If it is searching through the whole collection, is there a way to terminate after the first match and save the time spent on looking through all the documents?

Many thanks in advance!

Please read carefully. It is totally dependant on the use-case you are implementing. The use-case of the other post was to determine if there was 0 or at least one related document in the $lookup-ed collection. So you do not need to $lookup at all the related documents. So it is wise to stop when you found one. Not all use-case only needs to $lookup at only one. But if you only need one then $limit:1 is helpful.

Yes it is.

Thank you, yes that is how I meant it as well.
Thanks again for the confirmation :))

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.