Database Reference
In-Depth Information
at this time, the geospatial implementation is based on the idea that the world is a perfect sphere. thus, each
degree of latitude and longitude is exactly 111km (69 miles) in length. however, this is only true exactly at the equator;
the further you move away from the equator, the smaller each degree of longitude becomes, approaching zero at the poles.
Note
Querying Geospatial Information
In this chapter, we are concerned primarily with two things: how to model the data and how a database works in the
background of an application. That said, manipulating geospatial information is increasingly important in a wide
variety of applications, so we'll take a few moments to explain how to leverage geospatial information in a MongoDB
database.
Before getting started, a mild word of caution. If you are completely new to MongoDB and haven't had the
opportunity to work with (geospatial) indexed data in the past, this section may seem a little overwhelming at first.
Not to worry, however; you can safely skip it for now and come back to it later if you wish to. The examples given
serve to show you a practical example of how (and why) to use geospatial indexing, making it easier to comprehend.
With that out of the way, and if you are feeling brave, read on.
Once you've added data to your collection, and once the index has been created, you can do a geospatial query.
For example, let's look at a few lines of simple yet powerful code that demonstrate how to use geospatial indexing.
Begin by starting up your MongoDB shell and selecting a database with the use function. In this case, the
database is named restaurants :
> use restaurants
Once you've selected the database, you can define a few documents that contain geospatial information, and
then insert them into the places collection (remember: you do not need to create the collection beforehand):
> db.restaurants.insert( { name: "Kimono", loc: { type: "Point", coordinates: [ 52.37045
1, 5.217497] } } )
> db.restaurants.insert( {name: "Shabu Shabu", loc: { type: "Point", coordinates: [51.9
15288,4.472786] } } )
> db.restaurants.insert( {name: "Tokyo Cafe", loc: { type: "Point", coordinates: [52.36
8736, 4.890530] } } )
After you add the data, you need to tell the MongoDB shell to create an index based on the location information
that was specified in the loc key, as in this example:
> db.restaurants.ensureIndex ( { loc: "2dsphere" } )
Once the index has been created, you can start searching for your documents. Begin by searching on an exact
value (so far this is a “normal” query; it has nothing to do with the geospatial information at this point):
> db.restaurants.find( { loc : [52,5] } )
>
 
 
Search WWH ::




Custom Search