- Reference >
- Operators >
- Query and Projection Operators >
- Geospatial Query Operators >
- $geoWithin
$geoWithin¶
Definition¶
- $geoWithin¶
New in version 2.4: $geoWithin replaces $within which is deprecated.
Selects documents with geospatial data that exists entirely within a specified shape. When determining inclusion, MongoDB considers the border of a shape to be part of the shape, subject to the precision of floating point numbers.
$geoWithin does not require a geospatial index. However, a geospatial index will improve query performance. Both 2dsphere and 2d geospatial indexes support $geoWithin.
The specified shape can be either a GeoJSON Polygon (either single-ringed or multi-ringed), a GeoJSON MultiPolygon, or a shape defined by legacy coordinate pairs.
To specify a GeoJSON Polygon (either single-ringed or multi-ringed) or MultiPolygon, $geoWithin uses the $geometry operator to specify the shape and has the following form:
{ <location field>: { $geoWithin: { $geometry: { type: <"Polygon" or "MultiPolygon"> , coordinates: [ <coordinates> ] } } } }
Important
If you use longitude and latitude, specify coordinates in order of longitude, latitude.
If querying for inclusion in a shape defined by legacy coordinate pairs on a plane, use the following syntax:
{ <location field>: { $geoWithin: { <shape operator>: <coordinates> } } }
The available shape operators are:
- $box,
- $polygon,
- $center (defines a circle), and
- $centerSphere (defines a circle on a sphere).
Behavior¶
The $geoWithin operator does not return sorted results. As such, MongoDB can return $geoWithin queries more quickly than geospatial $near or $nearSphere queries, which sort results.
For $geoWithin queries, GeoJSON geometries must have an area less than the area of a single hemisphere. For geometries larger than a single hemisphere, MongoDB queries for the smaller of the complementary geometries. For geometries equal to a single hemisphere, MongoDB makes no guarantees as to which geometry (the specified geometry or the complementary) it uses.
Example¶
The following example selects all loc data that exist entirely within a GeoJSON Polygon:
db.places.find(
{
loc: {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ]
}
}
}
}
)
- $within¶
Deprecated since version 2.4: $geoWithin replaces $within in MongoDB 2.4.