$box

Defines a rectangular area for geospatial queries using two coordinate pairs, useful for finding locations within a rectangular geographical boundary.

Syntax

{ <location field>: { $geoWithin: { $box: [<lower_left>, <upper_right>] } } }

Parameters

location fieldstringrequired

The field containing the geospatial data

lower_leftobjectrequired

Array of [longitude, latitude] specifying the bottom-left corner

upper_rightobjectrequired

Array of [longitude, latitude] specifying the top-right corner

Examples

Find stores within rectangular area

Find stores located within a specific rectangular area defined by coordinate pairs

Query:

db.stores.find({ location: { $geoWithin: { $box: [[-142.0012, -51.3041], [123.3403, 70.1272]] } } })

Output:

Documents where location falls within the specified rectangular boundary

Basic box query with projection

Find stores within a box area and return only name and location fields

Query:

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

Output:

Stores within the box area with limited field projection

Related