$polygon

Defines a polygon for geospatial queries, allowing you to find locations within an irregular shape, useful for querying locations within complex geographical boundaries.

Syntax

{ <location field>: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[<longitude1>, <latitude1>], ..., [<longitude1>, <latitude1>]]] } } } }

Parameters

location fieldstringrequired

The field containing the geospatial data

coordinatesobjectrequired

Array of coordinate pairs forming the polygon, with first and last points identical to close the polygon

Examples

Search within polygon boundary

Find stores that fall inside a custom polygon region

Query:

db.stores.find({ location: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[-141.9922, 16.8331], [-112.7858, -29.1866], [-38.4071, -47.2548], [-141.9922, 16.8331]]] } } } })

Output:

Stores located within the irregular polygon boundary

Polygon query with field selection

Find stores within polygon and return only specific fields

Query:

db.stores.find({ location: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[-141.9922, 16.8331], [-112.7858, -29.1866], [-38.4071, -47.2548], [-141.9922, 16.8331]]] } } } }, { name: 1, location: 1 })

Output:

Name and location of stores within the polygon area

Related