Database Reference
In-Depth Information
In addition to the
$geoNear
operator, MongoDB also includes a
$geoWithin
operator.
You use this operator to find items in a particular shape. At this time, you can find items
located in a
$box, $polygon, $center
and
$centerSphere
shape, where
$box
represents
a rectangle,
$polygon
represents a specific shape of your choosing,
$center
represents a
circle, and
$centerSphere
defines a circle on a sphere. Let's look at a couple of additional
examples that illustrate how to use these shapes.
■
With version 2.4 of MongoDB the
$within
operator was deprecated and replaced
by
$geoWithin
. this operator does not strictly require a geospatial indexing. also, unlike the
$near
operator,
$geoWithin
does not sort the returned results, improving their performance.
Note
To use the
$box
shape, you first need to specify the lower-left, followed by the
upper-right coordinates of the box, as in the following example:
> db.restaurants.find( { loc: { $geoWithin : { $box : [ [52.368549,
4.890238], [52.368849, 4.89094] ] } } } )
Similarly, to find items within a specific polygon form, you need to specify the
coordinates of your points as a set of nested arrays. Again note that the first and last
coordinates must be identical to close the shape properly, as shown in the following
example:
> db.restaurants.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[52.368739, 4.890203], [52.368872, 4.890477], [52.368726, 4.890793],
[52.368608, 4.89049], [52.368739, 4.890203]
] ]
}
}
} )
The code to find items in a basic
$circle
shape is quite simple. In this case, you
need to specify the center of the circle and its radius, measured in the units used by the
coordinate system, before executing the
find()
function:
> db.restaurants.find( { loc: { $geoWithin : { $center : [ [52.370524,
5.217682], 10] } } } )
Note that ever since MongoDB version 2.2.3, the
$center
operator can be used
without having a geospatial index in place. However, it is recommended to create one to
improve performance.