Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-58602

Rewrite $geoNear to $geoWithin + compute distance + $sort

    XMLWordPrintableJSON

Details

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: Major - P3 Major - P3
    • 5.2.0
    • None
    • None
    • None
    • ALL
    • QO 2021-09-06, QO 2021-09-20, QO 2021-10-04, QO 2021-10-18, QO 2021-11-01, QO 2021-11-15, QO 2021-11-29

    Description

      $geoNear sorts documents by their distance from a given query point. But its implementation is very tied to a particular index-scan plan, so it can only appear as the first stage in a pipeline.

      We can lift this restriction by splitting it up into separate stages. Using the new internal-only stage from SERVER-58745, we could rewrite it like this:

      {$geoNear: {
        key: <fieldname>,
        near: <point>,
        minDistance: <min>,
        maxDistance: <max>,
      }}
       
      =>
       
      {$match: { <fieldname>: {$geoWithin: {$centerSphere: [<point>, <max>]}} }}
      {$match: { <fieldname>: {$not: {$geoWithin: {$centerSphere: [<point>, <min>]}}} }}
      {$_internalGeoNearDistance: {
        key: <fieldname>,
        near: <point>,
      }}
      {$sort: {$meta: 'geoNearDistance'}}
      

      Splitting it up this way will allow other rewrites to optimize the $geoWithin and $sort.

      Attachments

        Activity

          People

            david.percy@mongodb.com David Percy
            david.percy@mongodb.com David Percy
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: