Navigation

$geoNear (aggregation)

On this page

Definition

$geoNear

Outputs documents in order of nearest to farthest from a specified point.

The $geoNear stage has the following prototype form:

{ $geoNear: { <geoNear options> } }

The $geoNear operator accepts a document that contains the following $geoNear options. Specify all distances in the same units as those of the processed documents’ coordinate system:

Field Type Description
spherical boolean

Determines how MongoDB calculates the distance between two points:

  • When true, MongoDB uses $nearSphere semantics and calculates distances using spherical geometry.
  • When false, MongoDB uses $near semantics: spherical geometry for 2dsphere indexes and planar geometry for 2d indexes.

Default: false.

limit number Optional. The maximum number of documents to return. The default value is 100. See also the num option.
num number Optional. The num option provides the same function as the limit option. Both define the maximum number of documents to return. If both options are included, the num value overrides the limit value.
maxDistance number

Optional. The maximum distance from the center point that the documents can be. MongoDB limits the results to those documents that fall within the specified distance from the center point.

Specify the distance in meters if the specified point is GeoJSON and in radians if the specified point is legacy coordinate pairs.

query document

Optional. Limits the results to the documents that match the query. The query syntax is the usual MongoDB read operation query syntax.

You cannot specify a $near predicate in the query field of the $geoNear stage.

distanceMultiplier number Optional. The factor to multiply all distances returned by the query. For example, use the distanceMultiplier to convert radians, as returned by a spherical query, to kilometers by multiplying by the radius of the Earth.
uniqueDocs boolean

Optional. If this value is true, the query returns a matching document once, even if more than one of the document’s location fields match the query.

Deprecated since version 2.6: Geospatial queries no longer return duplicate results. The $uniqueDocs operator has no impact on results.

near GeoJSON point or legacy coordinate pair

The point for which to find the closest documents.

If using a 2dsphere index, you can specify the point as either a GeoJSON point or legacy coordinate pair.

If using a 2d index, specify the point as a legacy coordinate pair.

distanceField string The output field that contains the calculated distance. To specify a field within an embedded document, use dot notation.
includeLocs string Optional. This specifies the output field that identifies the location used to calculate the distance. This option is useful when a location field contains multiple locations. To specify a field within an embedded document, use dot notation.
minDistance number

Optional. The minimum distance from the center point that the documents can be. MongoDB limits the results to those documents that fall outside the specified distance from the center point.

Specify the distance in meters for GeoJSON data and in radians for legacy coordinate pairs.

New in version 3.2.

key string

Optional. Specify the geospatial index to use when calculating the distance. If your collection has multiple geospatial indexes, you must use the key option to specify the indexed field path to use. Specify Which Geospatial Index to Use provides a full example.

If you do not specify the field over which to perform the search with key, MongoDB will attempt to look for a usable 2d or 2dsphere index, in that order. If there is more than one 2d index or more than one 2dsphere index, MongoDB will return an error.

New in version 4.0.

Behavior

When using $geoNear, consider that:

  • You can only use $geoNear as the first stage of a pipeline.

  • You must include the distanceField option. The distanceField option specifies the field that will contain the calculated distance.

  • $geoNear requires a geospatial index.

    If you have more than one geospatial index on the collection, use the keys parameter to specify which field to use in the calculation. If you have only one geospatial index, $geoNear implicitly uses the indexed field for the calculation.

  • You cannot specify a $near predicate in the query field of the $geoNear stage.
  • Views do not support geoNear operations (i.e. $geoNear pipeline stage and the deprecated geoNear command).

Generally, the options for $geoNear are similar to the deprecated geoNear command with the following exceptions:

  • distanceField is a mandatory field for the $geoNear pipeline operator; the option does not exist in the geoNear command.
  • includeLocs accepts a string in the $geoNear pipeline operator and a boolean in the geoNear command.

Example

Consider a collection places that has a 2dsphere index. The following aggregation finds at most 5 unique documents with a location at most 2 meters from the center [ -73.99279 , 40.719296 ] and have type equal to public:

db.places.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
        distanceField: "dist.calculated",
        maxDistance: 2,
        query: { type: "public" },
        includeLocs: "dist.location",
        num: 5,
        spherical: true
     }
   }
])

The aggregation returns the following:

{
   "_id" : 8,
   "name" : "Sara D. Roosevelt Park",
   "type" : "public",
   "location" : {
      "type" : "Point",
      "coordinates" : [ -73.9928, 40.7193 ]
   },
   "dist" : {
      "calculated" : 0.9539931676365992,
      "location" : {
         "type" : "Point",
         "coordinates" : [ -73.9928, 40.7193 ]
      }
   }
}

The matching document contains two new fields:

  • dist.calculated field that contains the calculated distance, and
  • dist.location field that contains the location used in the calculation.

Minimum Distance

New in version 3.2.

The following example uses the option minDistance to specify the minimum distance from the center point that the documents can be. MongoDB limits the results to those documents that fall outside the specified distance from the center point.

db.places.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
        distanceField: "dist.calculated",
        minDistance: 2,
        query: { type: "public" },
        includeLocs: "dist.location",
        num: 5,
        spherical: true
     }
   }
])

Specify Which Geospatial Index to Use

New in version 4.0.

Consider a places collection that has a 2dsphere index on the location field and a 2d index on the legacy field.

A document in the places collection resembles the following:

{
   "_id" : 3,
   "name" : "Polo Grounds",
   "location": {
      "type" : "Point",
      "coordinates" : [ -73.9375, 40.8303 ]
   },
   "legacy" : [ -73.9375, 40.8303 ],
   "category" : "Stadiums"
}

The following example uses the keys option to specify that the aggregation should use the location field values for the $geoNear operation rather than the legacy field values.

db.places.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -73.98142 , 40.71782 ] },
        key: "location",
        distanceField: "dist.calculated",
        query: { "category": "Parks" }
     }
   }
])

The aggregation returns the following:

{
   "_id" : 2,
   "name" : "Sara D. Roosevelt Park",
   "location" : {
      "type" : "Point",
      "coordinates" : [
         -73.9928,
         40.7193
      ]
   },
   "category" : "Parks",
   "dist" : {
      "calculated" : 974.175764916902
   }
}
{
   "_id" : 1,
   "name" : "Central Park",
   "location" : {
      "type" : "Point",
      "coordinates" : [
         -73.97,
         40.77
      ]
   },
   "legacy" : [
      -73.97,
      40.77
   ],
   "category" : "Parks",
   "dist" : {
      "calculated" : 5887.92792958097
   }
}