Database Reference
In-Depth Information
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.370451, 5.217497] } } )
> db.restaurants.insert( {name: "Shabu Shabu", loc: { type: "Point",
coordinates: [51.915288, 4.472786] } } )
> db.restaurants.insert( {name: "Tokyo Cafe", loc: { type: "Point",
coordinates: [52.368736, 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] } )
>
The preceding search returns no results. This is because the query is
too
specific.
A better approach in this case would be to search for documents that contain information
near
a given value. You can accomplish this using the
$near
operator. Note that this
requires the
type
operator to be specified, as in the following example:
> db.restaurants.find( { loc : { $geoNear : { $geometry : { type : "Point",
coordinates:
[52.338433, 5.513629] } } } } )
This produces the following output:
{
"_id" : ObjectId("51ace0f380523d89efd199ac"),
"name" : "Kimono",
"loc" : {
"type" : "Point",
"coordinates" : [ 52.370451, 5.217497 ]
}
}