Navigation
This version of the documentation is archived and no longer supported.
  • Indexes >
  • Geospatial Queries with 2d Indexes

Geospatial Queries with 2d Indexes

MongoDB provides support for querying location-based data using special geospatial indexes. For an introduction to these 2d indexes, see 2d Geospatial Indexes.

MongoDB supports the following geospatial query types:

  • Proximity queries, which select documents based on distance to a given point. See Proximity Queries.
  • Bounded queries, which select documents that have coordinates within a specified area. See Bounded Queries.
  • Exact queries, which select documents with an exact coordinate pair, which has limited applicability. See Query for Exact Matches.

Considerations

With the geoNear command, a collection can have only one 2d index. With geospatial query operators such as $near operator, a collection can have multiple geospatial indexes.

Proximity Queries

Proximity queries select the documents closest to the point specified in the query. To perform proximity queries you use either the find() method with the $near operator or you use the geoNear command.

The find() method with the $near operator returns 100 documents by default and sorts the results by distance. The $near operator uses the following form:

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

Example

The following query

db.places.find( { loc: { $near: [ -70, 40 ] } } )

returns output similar to the following:

{ "_id" : ObjectId(" ... "), "loc" : [ -73, 39 ] }

The geoNear command returns more information than does the $near operator. The geoNear command can only return a single 16-megabyte result set. The geoNear command also offers additional operators, such as operators to query for maximum or spherical distance. For a list of operators, see geoNear.

Without additional operators, the geoNear command uses the following form:

db.runCommand( { geoNear: <collection>, near: [ x, y ] } )

Example

The following command returns the same results as the $near in the previous example but with more information:

db.runCommand( { geoNear: "places", near: [ -74, 40.74 ] } )

This operation will return the following output:

{
   "ns" : "test.places",
   "results" : [
      {
         "dis" : 3,
         "obj" : {
            "_id" : ObjectId(" ... "),
            "loc" : [
               -73,
               39
            ]
         }
      }
   ],
   "stats" : {
      "time" : 2,
      "btreelocs" : 0,
      "nscanned" : 1,
      "objectsLoaded" : 1,
      "avgDistance" : 3,
      "maxDistance" : 3.0000188685220253
   },
   "near" : "0110000111111000000111111000000111111000000111111000",
   "ok" : 1
}

Distance Queries

You can limit a proximity query to those documents that fall within a maximum distance of a point. You specify the maximum distance using the units specified by the coordinate system. For example, if the coordinate system uses meters, you specify maximum distance in meters.

To specify distance using the find() method, use $maxDistance operator. Use the following form:

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

To specify distance with the geoNear command, use the maxDistance option. Use the following form:

db.runCommand( { geoNear: <collection>, near: [ x, y ], maxDistance: <distance> } )

Limit the Number of Results

By default, geospatial queries using find() method return 100 documents, sorted by distance. To limit the result when using the find() method, use the limit() method, as in the following prototype:

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

To limit the result set when using the geoNear command, use the num option. Use the following form:

db.runCommand( { geoNear: <collection>, near: [ x, y ], num: z } )

To limit geospatial search results by distance, see Distance Queries.

Bounded Queries

Bounded queries return documents within a shape defined using the $within operator. MongoDB’s bounded queries support the following shapes:

Bounded queries do not return sorted results. As a result MongoDB can return bounded queries more quickly than proximity queries. Bounded queries have the following form:

db.collection.find( { <location field> :
                           { "$within" :
                             { <shape> : <shape dimensions> }
                           }
                    } )

The following sections describe each of the shapes supported by bounded queries:

Circles

To query for documents with coordinates inside the bounds of a circle, specify the center and the radius of the circle using the $within operator and $center option. Consider the following prototype query:

db.collection.find( { "field": { "$within": { "$center": [ center, radius ] } } } )

The following example query returns all documents that have coordinates that exist within the circle centered on [-74, 40.74] and with a radius of 10, using a geospatial index on the loc field:

db.places.find( { "loc": { "$within":
                            { "$center": [ [-74, 40.74], 10 ] }
                         }
                } )

The $within operator using $center is similar to using $maxDistance, but $center has different performance characteristics. MongoDB does not sort queries that use the $within operator are not sorted, unlike queries using the $near operator.

Rectangles

To query for documents with coordinates inside the bounds of a rectangle, specify the lower-left and upper-right corners of the rectangle using the $within operator and $box option. Consider the following prototype query:

db.collection.find( { "field": { "$within": { "$box": [ coordinate0, coordinate1 ] } } } )

The following query returns all documents that have coordinates that exist within the rectangle where the lower-left corner is at [ 0, 0 ] and the upper-right corner is at [ 3, 3 ], using a geospatial index on the loc field:

db.places.find( { "loc": { "$within": { "$box": [ [0, 0] , [3, 3] ] } } } )

Polygons

New in version 1.9: Support for polygon queries.

To query for documents with coordinates inside of a polygon, specify the points of the polygon in an array, using the $within operator with the $polygon option. MongoDB automatically connects the last point in the array to the first point. Consider the following prototype query:

db.places.find({ "loc": { "$within": { "$polygon": [ points ] } } })

The following query returns all documents that have coordinates that exist within the polygon defined by [ [0,0], [3,3], [6,0] ]:

db.places.find({ "loc": { "$within": { "$polygon":
                                     [ [ 0,0], [3,3], [6,0] ] } } } )

Query for Exact Matches

You can use the db.collection.find() method to query for an exact match on a location. These queries have the following form:

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

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

Exact geospatial queries only applicability for a limited selection of cases, the proximity and bounded queries provide more useful results for more applications.

Calculate Distances Using Spherical Geometry

When you query using the 2d index, MongoDB calculates distances using flat geometry by default, which models points on a flat surface.

Optionally, you may instruct MongoDB to calculate distances using spherical geometry, which models points on a spherical surface. Spherical geometry is useful for modeling coordinates on the surface of Earth.

To calculate distances using spherical geometry, use MongoDB’s spherical query operators and options:

See also

Geospatial.

For more information on differences between flat and spherical distance calculation, see Distance Calculation.

Distance Multiplier

The distanceMultiplier option geoNear returns distances only after multiplying the results by command by an assigned value. This allows MongoDB to return converted values, and removes the requirement to convert units in application logic.

Note

Because distanceMultiplier is an option to geoNear, the multiplication operation occurs on the mongod process. The operation adds a slight overhead to the operation of geoNear.

Using distanceMultiplier in spherical queries allows one to use results from the geoNear command without radian to distance conversion. The following example uses distanceMultiplier in the geoNear command with a spherical example:

db.runCommand( { geoNear: "places",
                 near: [ -74, 40.74 ],
                 spherical: true,
                 distanceMultiplier: 3963.192
               }  )

The output of the above operation would resemble the following:

{
   // [ ... ]
   "results" : [
      {
         "dis" : 73.46525170413567,
         "obj" : {
            "_id" : ObjectId( ... )
            "loc" : [
               -73,
               40
            ]
         }
      }
   ],
   "stats" : {
      // [ ... ]
      "avgDistance" : 0.01853688938212826,
      "maxDistance" : 0.01853714811400047
   },
   "ok" : 1
}

See also

The Distance operator.

Querying Haystack Indexes

Haystack indexes are a special 2d geospatial index that optimized to return results over small areas. To create geospatial indexes see Haystack Indexes.

To query the haystack index, use the geoSearch command. You must specify both the coordinate and other field to geoSearch, which take the following form:

db.runCommand( { geoSearch: <collection>,
                 search: { <field>: <value> } } )

For example, to return all documents with the value restaurants in the type field near the example point, the command would resemble:

db.runCommand( { geoSearch: "places",
                 search: { type: "restaurant" },
                 near: [-74, 40.74] } )

Note

Haystack indexes are not suited to returning a full list of the closest documents to a particular location, as the closest documents could be far away compared to the bucketSize.

Note

Spherical query operations are not currently supported by haystack indexes.

The find() method and geoNear command cannot access the haystack index.