Database Reference
In-Depth Information
Implementing Geospatial Indexing
As Chapter 1briefly mentioned, MongoDB has implemented
geospatial
indexing
since
version 1.4. This means that, in addition to normal indexes, MongoDB also supports
geospatial indexes that are designed to work in an optimal way with location-based
queries. For example, you can use this feature to find a number of closest known items
to the user's current location. Or you might further refine your search to query for a
specified number of restaurants near the current location. This type of query can be
particularly helpful if you are designing an application where you want to find the closest
available branch office to a given customer's ZIP code.
A document for which you want to add geospatial information must contain either a
subobject or an array whose first element specifies the object type, followed by the item's
longitude and latitude, as in the following example:
> db.restaurants.insert({name: "Kimono", loc: { type: "Point",
coordinates: [ 52.370451, 5.217497] } } )
Note that the
type
parameter can be used to specify the document's object type,
which can be a
Point
, a
LineString
or a
Polygon
. As can be expected, the
Point
type is
used to specify that the item (in this case, a restaurant) is located at exactly the spot given,
thus requiring exactly two values, the longitute and latitude. The
LineString
type can be
used to specify that the item extends along a specific line (say, a street), and thus requires
a beginning and end point, as in the following example:
> db.streets.insert( {name: "Westblaak", loc: { type: "LineString",
coordinates: [ [52.36881, 4.890286],[52.368762, 4.890021] ] } } )
The
Polygon
type can be used to specify a (nondefault) shape (say, a shopping area).
When using this type, you need to ensure that the first and last points are identical, to
close the loop. Also, the point coordinates are to be provided as an array within an array,
as in the following example:
> db.stores.insert( {name: "SuperMall", loc: { type: "Polygon", coordinates:
[ [ [52.146917, 5.374337], [52.146966, 5.375471], [52.146722, 5.375085],
[52.146744, 5.37437], [52.146917, 5.374337] ] ] } } )
In most cases, the
Point
type will be appropriate.
Once this geospatial information is added to a document, you can create the index
(or even create the index beforehand, of course) and give the
ensureIndex()
function the
2dsphere
parameter:
> db.restaurants.ensureIndex( { loc: "2dsphere" } )