Victor Queiroz

MongoDB: Radius Search with Coordinates Using $geoWithin and $centerSphere

Recently I ran into the following problem:

I needed to check whether a list of coordinates was within a given radius. At first, I thought about using the Google Maps API, but the only feature that does this kind of search is available only in the JavaScript version, and my API was written in Node.js — it would be a bit complicated to use extra quota for a geographic search… Until I discovered MongoDB’s $centerSphere and $geoWithin, and that’s when I realized that MongoDB really is the database of the future… Hahaha.

Requirements

  • MongoDB 3.0

First, as stated in the MongoDB documentation about $centerSphere, you need to know that latitude and longitude coordinates must be inside an Array for MongoDB to perform the search, something like this:

{
  "name": "Victor Queiroz",
  "address": {
    "coords": [
      7.0202512,
      4.8499534
    ]
  }
}

The query should be written as follows:

var coords = [
  7.0398232,
  4.8492161
];

var miles = 1.8;

db.users.find({
  'address.coords': {
    $geoWithin: {
      $centerSphere: [
        coords,
        miles / 3963.2
      ]
    }
  }
})

MongoDB will define a circle of X miles, with coords as the center of the radius, and will search within address.coords looking for coordinates that fall inside this circle.

In this case, I defined a radius of 1.8 miles, which is equivalent to 3 km. Again: it will return all documents that are within this radius.

Remember that longitude must come BEFORE latitude in the arrays.

Below are some basic descriptions of the operators we used in this query:

$centerSphere

{
  <location field>: {
    $geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] }
  }
}

Defines a circle for any geospatial query that uses spherical geometry.

$geoWithin

{
  <location field>: {
    $geoWithin: {
      $geometry: {
        type: <"Polygon" or "MultiPolygon">,
        coordinates: [ <coordinates> ]
      }
    }
  }
}

Selects documents with geospatial data that exist entirely within a specified shape. When determining inclusion, MongoDB considers the boundary of a shape as part of the shape, subject to the precision of floating-point numbers.

For more information, visit the official MongoDB documentation and read about it.

I hope this article helps many of you the way it helped me. Cheers.

Comments