5.6 Geospatial query operator $geoIntersects and LineString

The operator $geoIntersects selects documents whose geospatial data intersects with a specified GeoJSON object. With the default coordinate reference system (CRS), the syntax is:

{
  <location field>: {
     $geoIntersects: {
        $geometry: {
           type: "<GeoJSON object type>" ,
           coordinates: [  ]
        }
     }
  }
}

LineString is a geometry object that defines a line by two or more points.

When assigning to the geometry field the values from coordinates field, the coordinates fields with only one pair of coordinates (latitude and longitude) were converted to the type Point, and those with more than one pair of coordinates were converted to the type Multipoint. However, the LineString type is more appropriate for streets and avenues than Multipoint, because these are actually lines on the map. So let’s convert the coordinates of streets and avenues into LineString using the command:

db.pages.find(
  { $and:
    [
      {
        "coordinates": { "$gt": [] }
      },
      { $or:
        [
          { title : RegExp('^Rua')},
          { title : RegExp('^Avenida') }
        ]
      }
    ]
  }
).forEach(function(data) {
  var geometria = {
      type: "LineString",
      coordinates: data.coordinates
  };
  data.geometry = geometria;
  db.pages.save(data);
});

After this transformation we will list the streets crossing Uruguaiana Street using the command:

> db.pages.find(
...   {
...     geometry: {
...       $geoIntersects: {
...         $geometry: {
...           type: "LineString" ,
...           coordinates: [
...             [ -43.17866, -22.90638 ],
...             [ -43.17984, -22.90458 ],
...             [ -43.18016, -22.90405 ],
...             [ -43.18057, -22.90349 ],
...             [ -43.18147, -22.90205 ],
...             [ -43.18214, -22.90094 ]
...           ]
...         }
...       }
...     }
...   }, { title: 1, _id: 0}
... );
{ "title" : "Rua do Sabão" }
{ "title" : "Rua da Alfândega" }
{ "title" : "Rua da Vala" }
{ "title" : "Rua São Pedro" }
{ "title" : "Rua das Violas" }
{ "title" : "Rua Detrás do Hospício" }
{ "title" : "Rua do Rosário" }
{ "title" : "Rua do Ouvidor" }
{ "title" : "Rua do Cano" }
{ "title" : "Rua do Piolho" }
>

Rua da Vala is an old name of Rua Uruguaiana, so its coordinates overlap.

5. Geospatial queries