Location-based Apps with MongoDB: GeoSpatial Indexing

As mentioned in the previous section on indexes, MongoDB has support for two kinds of index: Btree and geospatial. Btree indexes have been covered quite thoroughly in the preceeding section, however we have not yet described GeoSpatial indexes.

First of all, let us discuss why geospatial indexing might be useful at all. Many apps today are being built with the requirement of location-awareness. Typically this translates into features where points of interest (POI) near a particular user location may be rapidly retrieved from a database. For example, a location-aware mobile app might wish to quickly fetch a list of nearby coffeeshops, based upon the current GPS co-ordinates. The complicating issue, fundamentally, is that the world is both quite large and quite full of interesting points—and so to try to answer such a query by iterating through the entire list of all POIs in the world to find ones which are nearby would take an unacceptably long time. Hence the need for some sort of GeoSpatial indexing, to speed up these searches.

Fortunately for anybody tasked with building location-aware applications, MongoDB is one of the rare few databases with out-of-the-box support for geospatial indexing. MongoDB uses geohashing, a public domain algorithm developed by Gustavo Niemeyer, which translates geographic proximity into lexical proximity. Hence, a database supporting range queries (such as MongoDB) can be efficiently used to query ...

Get MongoDB and Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.