title: MongoDB: Matching points from one collection with polygons from another
body: <p>I'm trying to match points in one collection with regions stored in another collection.
  Here are examples of documents.</p>
  <p>Points:</p>
  <pre><code>{ 
    &quot;_id&quot; : ObjectId(&quot;5e36d904618c0ea59f1eb04f&quot;), 
    &quot;gps&quot; : { &quot;lat&quot; : 50.073288, &quot;lon&quot; : 14.43979 },  
    &quot;timeAdded&quot; : ISODate(&quot;2020-02-02T15:13:22.096Z&quot;) 
  }
  </code></pre>
  <p>Regions:</p>
  <pre><code>{
    &quot;_id&quot; : ObjectId(&quot;5e49a469afae4a11c4ff3cf7&quot;), 
    &quot;type&quot; : &quot;Feature&quot;, 
    &quot;geometry&quot; : { 
      &quot;type&quot; : &quot;Polygon&quot;, 
      &quot;coordinates&quot; : [ 
        [ 
          [ -748397.88, -1049211.61 ], 
          [ -748402.77, -1049212.2 ],
          ... 
          [ -748410.41, -1049213.11 ], 
          [ -748403.05, -1049070.62 ]
        ] 
      ] 
    }, 
    &quot;properties&quot; : {  
      &quot;Name&quot; : &quot;Region 1&quot; 
    } 
  }
  </code></pre>
  <p>And the query I'm trying to construct is something like this:</p>
  <pre><code>db.points.aggregate([
    {$project: {
      coordinates: [&quot;$gps.lon&quot;, &quot;$gps.lat&quot;]
    }}, 
    {$lookup: {
      from: &quot;regions&quot;, pipeline: [
        {$match: {
          coordinates: {
            $geoWithin: {
              $geometry: {
                type: &quot;Polygon&quot;, 
                coordinates: &quot;$geometry.coordinates&quot;
              }
            }
          }
        }}
      ], 
      as: &quot;district&quot;
    }}
  ])
  </code></pre>
  <p>I'm getting an error:</p>
  <blockquote>
  <p>assert: command failed: {</p>
  <pre><code>    &quot;ok&quot; : 0,
      &quot;errmsg&quot; : &quot;Polygon coordinates must be an array&quot;,
      &quot;code&quot; : 2,
      &quot;codeName&quot; : &quot;BadValue&quot;
  </code></pre>
  <p>} : aggregate failed</p>
  </blockquote>
  <p>I've noticed the structure of $geoWithin document is same as structure of one I have for each region. So I tried such query:</p>
  <pre><code>db.points.aggregate([
    {$project: {
      coordinates: [&quot;$gps.lon&quot;, &quot;$gps.lat&quot;]
    }}, 
    {$lookup: {
      from: &quot;regions&quot;, pipeline: [
        {$match: {
          coordinates: {
            $geoWithin: &quot;$geometry.coordinates&quot;
          }
        }}
      ], 
      as: &quot;district&quot;
    }}
  ])
  </code></pre>
  <p>The error was same.</p>
  <p>I looked up for geoqueries but surprisingly all found mentions had static region document instead of one taken from a collection. So I'm wondering - is it ever possible to map points with regions having that both document collections aren't static and taken from DB?</p>