Database Reference
In-Depth Information
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 ]
}
}
{
"_id" : ObjectId("51ace13380523d89efd199ae"),
"name" : "Tokyo Cafe",
"loc" : {
"type" : "Point",
"coordinates" : [ 52.368736, 4.89053 ]
}
}
{
"_id" : ObjectId("51ace11b80523d89efd199ad"),
"name" : "Shabu Shabu",
"loc" : {
"type" : "Point",
"coordinates" : [ 51.915288, 4.472786 ]
}
}
Although this set of results certainly looks better, there's still one problem: all of the documents are returned!
When used without any additional operators, $near returns the first 100 entries and sorts them based on their
distance from the given coordinates. Now, while we can choose to limit our results to say, the first two items (or two
hundred, if we want) using the limit function, even better would be to limit the results to those within a given range.
This can be achieved by appending the $maxDistance operator. Using this operator you can tell MongoDB to
return only those results falling within a maximum distance (measured in meters) from the given point, as in the
following example and its output:
> db.retaurants.find( { loc : { $geoNear : { $geometry : { type : "Point", coordinates:
[52.338433,5.513629] }, $maxDistance : 40000 } } } )
{
"_id" : ObjectId("51ace0f380523d89efd199ac"),
"name" : "Kimono",
"loc" : {
"type" : "Point",
"coordinates" : [ 52.370451, 5.217497 ]
}
}
 
Search WWH ::




Custom Search