MongoDB Geospatial queries in Meteor
While adding a new feature to a client's web app, I need to add the ability to query data by location and within a certain radius. This is referred to as a geospatial query. Essentially, you provide a location and radius, and results within that area are returned.
Although reasonably easy to do, there are a few steps to the process to get it to work.
First step - GeoJSON
The first thing is to ensure that your data structure is in order to allow these geospatial queries. The structure needs to conform to the GeoJSON format. This is added to the data that is going to be queried. The structure is as follows:
The important things to note about this structure is that we are declaring it as a type of point
and the the order of the coordinates is reversed. longitude
comes first!
This structure is not limited to the above structure but this is what I needed for my applications. More information can be found in the mongodb docs.
Next step - Ensuring the index
Now that we have added the GeoJSON to our data structure we now need to add the index to our mongodb collection. This allows us to perform these geospatial queries. This can be performed with the following code. Obviously Locations
is the name of my collection, you will need to switch this out for your collection name.
You can check if this was successful by opening your mongo client and viewing the indexes for that collection.
Final step - query to your hearts content
Now that the GeoJSON and index is set up you can now get querying. The query below is part of an API call that provides longitude
, latitude
and radius as body params.
When using $centerSphere
, the second argument is the radius in radians, so it must be divided by the radius of the earth in miles. More information on how to calculate distance using spherical geometry can be found here
When using this type of query in Meteor it is important to remember that minimongo does not support $geoWithin
so this type of query must be performed on the server.
Conclusion
I hope this short insight helps others use this awesome feature of MongoDB.