Database Reference
In-Depth Information
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.37045
1, 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" } )
the ensureIndex() function is used to add a custom index. Don't worry about the syntax of this function
yet—you will learn how to use ensureIndex() in depth in the next chapter.
Note
The 2dsphere parameter tells ensureIndex() that it's indexing a coordinate or some other form of two-dimensional
information on an Earth-like sphere. By default, ensureindex() assumes that a latitude/longitude key is given, and it
uses a range of -180 to 180 . However, you can overwrite these values using the min and max parameters:
> db.restaurants.ensureIndex( { loc: "2dsphere" }, { min : -500 , max : 500 } )
You can also expand your geospatial indexes by using secondary key values (also known as compound keys ). This
structure can be useful when you intend to query on multiple values, such as a location (geospatial information) and a
category (sort ascending):
> db.restaurants.ensureIndex( { loc: "2dsphere", category: 1 } )
 
 
Search WWH ::




Custom Search