This version of the documentation is archived and no longer supported.



The $within operator allows you to select items that exist within a shape on a coordinate system for geospatial queries. This operator uses the following syntax:

db.collection.find( { location: { $within: { shape } } } );

Replace { shape } with a document that describes a shape. The $within command supports the following shapes. These shapes and the relevant expressions follow:

  • Rectangles. Use the $box operator, consider the following variable and $within document:

    db.collection.find( { location: { $within: { $box: [[100,0], [120,100]] } } } );

    Here a box, [[100,120], [100,0]] describes the parameter for the query. As a minimum, you must specify the lower-left and upper-right corners of the box.

  • Circles. Use the $center operator. Specify circles in the following form:

    db.collection.find( { location: { $within: { $center: [ center, radius } } } );
  • Circular distance on a sphere. Use the $centerSphere operator. For the syntax, see $centerSphere.

  • Polygons. Use the $polygon operator. Specify polygons with an array of points. See the following example:

    db.collection.find( { location: { $within: { $polygon: [[100,120], [100,100], [120,100], [240,200]] } } } );

    The last point of a polygon is implicitly connected to the first point.

All shapes include the border of the shape as part of the shape, although this is subject to the imprecision of floating point numbers.

Use $uniqueDocs to control whether documents with many location fields show up multiple times when more than one of its fields match the query.

Changed in version 2.2.3: Before 2.2.3, a geospatial index must exist on a field holding coordinates before using any of the geolocation query operators. After 2.2.3, applications may use geolocation query operators without having a geospatial index; however, geospatial indexes will support much faster geospatial queries than the unindexed equivalents.


A geospatial index must exist on a field and the field must hold coordinates before you can use any of the geolocation query operators.

←   $where $addToSet  →