$geoWithin

Selects documents whose location field falls completely within a specified geometry, supporting various shape operators including $box, $polygon, $center, and $geometry.

Syntax

{ <location field>: { $geoWithin: { <shape operator>: <shape definition> } } }

Parameters

location fieldstringrequired

The field containing the location coordinates

shape operatorstringrequired

Shape operator: $box, $center, $centerSphere, $polygon, or $geometry

shape definitionobjectrequired

The specific shape definition based on the chosen shape operator

Examples

Find stores within box area

Use $geoWithin with $box to find stores in rectangular area

Query:

db.stores.find({ location: { $geoWithin: { $box: [[65.0, 65.0], [75.0, 75.0]] } } })

Output:

Stores located within the specified rectangular box area

Find stores within circular area

Use $geoWithin with $center for circular area queries

Query:

db.stores.find({ location: { $geoWithin: { $center: [[-82.5543, -65.105], 5] } } })

Output:

Stores located within the circular area defined by center and radius

Find stores within polygon geometry

Use $geoWithin with $geometry for complex polygon searches

Query:

db.stores.find({ location: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[-85.0, -70.0], [-85.0, -60.0], [-75.0, -60.0], [-75.0, -70.0], [-85.0, -70.0]]] } } } })

Output:

Stores completely contained within the polygon boundary

Related