$box

Definition

  • $box
  • Specifies a rectangle for a geospatial$geoWithinquery to return documents that are within the bounds of therectangle, according to their point-based location data. When usedwith the $box operator, $geoWithin returnsdocuments based on grid coordinates and does not queryfor GeoJSON shapes.

To use the $box operator, you must specify the bottomleft and top right corners of the rectangle in an array object:

  1. {
  2. <location field>: {
  3. $geoWithin: {
  4. $box: [
  5. [ <bottom left coordinates> ],
  6. [ <upper right coordinates> ]
  7. ]
  8. }
  9. }
  10. }

Important

If you use longitude and latitude, specify longitude first.

Behavior

The query calculates distances using flat (planar) geometry.

Applications can use $boxwithout having a geospatial index.However, geospatial indexes support much faster queries than theunindexed equivalents.

Only the 2d geospatial index supports $box.

Example

The following example query returns all documents that are within thebox having points at: [ 0 , 0 ], [ 0 , 100 ], [ 100 , 0 ],and [ 100 , 100 ].

  1. db.places.find( {
  2. loc: { $geoWithin: { $box: [ [ 0, 0 ], [ 100, 100 ] ] } }
  3. } )