Query a 2d Index

The following sections describe queries supported by the 2d index.

Points within a Shape Defined on a Flat Surface

To select all legacy coordinate pairs found within a given shape on a flatsurface, use the $geoWithin operator along with a shapeoperator. Use the following syntax:

  1. db.<collection>.find( { <location field> :
  2. { $geoWithin :
  3. { $box|$polygon|$center : <coordinates>
  4. } } } )

The following queries for documents within a rectangle defined by [ 0, 0 ] at the bottom left corner and by [ 100 , 100 ] at the topright corner.

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

The following queries for documents that are within the circle centeredon [ -74 , 40.74 ] and with a radius of 10:

  1. db.places.find( { loc: { $geoWithin :
  2. { $center : [ [-74, 40.74 ] , 10 ]
  3. } } } )

For syntax and examples for each shape, see the following:

Points within a Circle Defined on a Sphere

MongoDB supports rudimentary spherical queries on flat 2d indexes forlegacy reasons. In general, spherical calculations should use a 2dsphereindex, as described in 2dsphere Indexes.

To query for legacy coordinate pairs in a “spherical cap” on a sphere,use $geoWithin with the $centerSphere operator.Specify an array that contains:

Use the following syntax:

  1. db.<collection>.find( { <location field> :
  2. { $geoWithin :
  3. { $centerSphere : [ [ <x>, <y> ] , <radius> ] }
  4. } } )

The following example query returns all documents within a 10-mileradius of longitude 88 W and latitude 30 N. The exampleconverts distance to radians by dividing distance by the approximateequatorial radius of the earth, 3963.2 miles:

  1. db.<collection>.find( { loc : { $geoWithin :
  2. { $centerSphere :
  3. [ [ 88 , 30 ] , 10 / 3963.2 ]
  4. } } } )

Proximity to a Point on a Flat Surface

Proximity queries return the legacy coordinate pairs closest to thedefined point and sort the results by distance. Use either the$near operator. The operator requires a 2d index.

The $near operator uses the following syntax:

  1. db.<collection>.find( { <location field> :
  2. { $near : [ <x> , <y> ]
  3. } } )

For examples, see $near.

Exact Matches on a Flat Surface

You cannot use a 2d index to return an exact match for acoordinate pair. Use a scalar, ascending or descending, index on afield that stores coordinates to return exact matches.

In the following example, the find()operation will return an exact match on a location if you have a {'loc': 1} index:

  1. db.<collection>.find( { loc: [ <x> , <y> ] } )

This query will return any documents with the value of [ <x> , <y> ].