title: Mongodb - Find the nearest point to a supplied polygon
body: <p>I have a mongodb collection that contains many documents. An attribute of these documents is a 2D point cloud collection that I currently query to find documents where any points sit inside a polygon etc. This works brilliantly.</p>
  
  <p>What I am looking to do now, and I am not sure if its actually possible is to be able to find the closest point in each point cloud collection to a supplied polygon.</p>
  
  <p>To give a visualization, Imagine the documents contain a 2D point cloud that represents a scan of a road tunnel. I want to be able to supply a polygon representing a lorry and find the closest point to it. This would be on a document basis so in English we would be asking the following:</p>
  
  <pre><code>result = nearest point to &lt;Polygon&gt; in document &lt;Document X&gt;.&lt;CloudPoints&gt;
  </code></pre>
  
  <p>Bonus - If it were possible to be able to return all documents with that result attached somehow, that would be even better though I suspect this is well outside the normal bounds of how Mongo is designed to be used.</p>
  
  <p>EDIT:</p>
  
  <p>By request, here is an example. Consider we have a collection of documents that look like the following. In this example I have many documents that have a collection of coordinates  that represent the locations of birds nests that happen to be protected, with laws etc as to how close a company can do ground works.</p>
  
  <pre><code>BirdsNests &gt;
          _id : 1234
          _Description : North town pipe replacement 2016
          _NestLocations &gt;
                        [100, 150]
                        [140, 180]
                        [165. 134]
                        etc...
  </code></pre>
  
  <p>If I supply a polygon, what I want to know is that the closest point in the Coordinates collection is to that polygon. Note: this should be to any surface of it such as. This will allow people to supply a polygon representing a proposed work site and have Mongo report which nest sits closest to the site parameter.</p>
  
  <p><img src="https://i.stack.imgur.com/ez4js.png" alt="enter image description here"></p>
  
  <p>This will be requested on a document basis initially so we would be asking for document 1234, what is the closest coordinate in the collection to this supplied polygon.</p>
  
  <p>Please note all examples used are purely fictional.</p>