Are you using the right Mongo geospatial query?

By Orta Therox

We recently got a report from one of our galleries in the Los Angeles area that they weren’t showing up on our Los Angeles exhibition listings.

make the cut.

Case closed. Or so I thought.

After some back and forth with our partner I decided to investigate more thoroughly, this time using some tricks of the trade from my other life outside of Artsy.

Casting a wider net

If there was something wrong with our 25km radius query, I wanted to start by casting a wider net and visualizing the results.

I modified the above query to cast a 50km net in order to see if there were some edges cases that needed scrutiny. Taking the resulting JSON response, I fired up Placemark, my favorite new tool for wrangling geospatial data.

(Incidentally I recommend reading Tom Macwright’s recent reflection on creating Placemark as a bootstrapped indie developer.)

Screenshot of a visualization in Placemark showing Los Angeles area exhibitions within a 50km radius.
All shows within a 50km radius

More than one way to draw a circle on the Earth

It was at this point that I recalled the specific form of the geospatial query our code was performing, and consulted the MongoDB docs for the $geoWithin query.

Turns out that you can invoke this as a radius query in one of two ways, by specifying $center or $centerSphere.

Per the docs for $center, this query…

calculates distances using flat (planar) geometry

Let us pause for a moment to note that while only some maps are deceitful, all maps are untruths. In the sense that they flatten three dimensions down to two, and inevitably distort the world in the process.

A postscript on map distortion

This corresponds to what you get when you use MongoDB’s $geoWithin $center query on geospatial data:

But we hope that understanding this crucial distinction between planar ($center) and spherical ($centerSphere) calculations will help you make the right choice when devising your own radius queries with MongoDB or other geospatial engines.