$geoNear (aggregation)

Definition

  • $geoNear
  • Outputs documents in order of nearest to farthest from a specifiedpoint.

Note

Starting in version 4.2, MongoDB removes the limit and numoptions for the $geoNear stage as well as the defaultlimit of 100 documents. To limit the results of$geoNear, use the $geoNear stage with the$limit stage.

The $geoNear stage has the following prototype form:

  1. { $geoNear: { <geoNear options> } }

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

FieldTypeDescriptionnearGeoJSON point or legacy coordinate pairThe point for which to find the closest documents.

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

If using a 2d index, specify the point as a legacycoordinate pair.distanceFieldstringThe output field that contains thecalculated distance. To specify a field within an embedded document,use dot notation.sphericalbooleanOptional. Determines how MongoDB calculates the distance between two points:

  • When true, MongoDB uses $nearSphere semantics andcalculates distances using spherical geometry.
  • When false, MongoDB uses $near semantics:spherical geometry for 2dsphereindexes and planar geometry for 2d indexes.Default: false.maxDistancenumberOptional. The maximum distance from the center point that the documents _can_be. MongoDB limits the results to those documents that fall withinthe specified distance from the center point.

Specify the distance in meters if the specified point isGeoJSON and in radians if the specified point islegacy coordinate pairs.querydocumentOptional. Limits the results to the documents that match the query. The querysyntax is the usual MongoDB read operation query syntax.

You cannot specify a $near predicate in the query field ofthe $geoNear stage.distanceMultipliernumberOptional. The factor to multiply all distances returned by the query. Forexample, use the distanceMultiplier to convert radians, asreturned by a spherical query, to kilometers by multiplying by theradius of the Earth.includeLocsstringOptional. This specifies the output field that identifies the location used tocalculate the distance. This option is useful when a location fieldcontains multiple locations. To specify a field within anembedded document, use dot notation.uniqueDocsbooleanOptional. If this value is true, the query returns a matching document once,even if more than one of the document’s location fields match thequery.

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

minDistancenumberOptional. The minimum distance from the center point that the documents canbe. MongoDB limits the results to those documents that fall outsidethe specified distance from the center point.

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

New in version 3.2.

keyOptional. Specify the geospatial indexed field to use when calculating thedistance.

If your collection has multiple 2d and/or multiple 2dsphereindexes, you must use the key option to specify the indexedfield path to use. Specify Which Geospatial Index to Useprovides a full example.

If there is more than one 2d index or more than one 2dsphereindex and you do not specify a key, MongoDB will return an error.

If you do not specify the key, and you have at most only one2d index and/or only one 2dsphere index, MongoDB looks firstfor a 2d index to use. If a 2d index does not exists, thenMongoDB looks for a 2dsphere index to use.

New in version 4.0.

Behavior

When using $geoNear, consider that:

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

  • You must include the distanceField option. ThedistanceField option specifies the field that will containthe calculated distance.

  • $geoNear requires a geospatial index.

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

  • You cannot specify a $near predicate in the query field ofthe $geoNear stage.
  • Views do not support geoNear operations (i.e.$geoNear pipeline stage).
  • Starting in version 4.2, $geoNear no longer has a defaultlimit of 100 documents.

Example

Note

Starting in version 4.2, MongoDB removes the limit and numoptions for the $geoNear stage as well as the defaultlimit of 100 documents. To limit the results of$geoNear, use the $geoNear stage with the$limit stage.

Consider a collection places that has a 2dsphere index. Thefollowing aggregation uses $geoNear to find documents witha location at most 2 meters from the center [ -73.99279 , 40.719296] and category equal to Parks.

  1. db.places.aggregate([
  2. {
  3. $geoNear: {
  4. near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
  5. distanceField: "dist.calculated",
  6. maxDistance: 2,
  7. query: { category: "Parks" },
  8. includeLocs: "dist.location",
  9. spherical: true
  10. }
  11. }
  12. ])

The aggregation returns the following:

  1. {
  2. "_id" : 8,
  3. "name" : "Sara D. Roosevelt Park",
  4. "category" : "Parks",
  5. "location" : {
  6. "type" : "Point",
  7. "coordinates" : [ -73.9928, 40.7193 ]
  8. },
  9. "dist" : {
  10. "calculated" : 0.9539931676365992,
  11. "location" : {
  12. "type" : "Point",
  13. "coordinates" : [ -73.9928, 40.7193 ]
  14. }
  15. }
  16. }

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 thecalculation.

Minimum Distance

Note

Starting in version 4.2, MongoDB removes the limit and numoptions for the $geoNear stage as well as the defaultlimit of 100 documents. To limit the results of$geoNear, use the $geoNear stage with the$limit stage.

The following example uses the option minDistance to specifythe minimum distance from the center point that the documents can be.The following aggregation finds all documents that

  1. db.places.aggregate([
  2. {
  3. $geoNear: {
  4. near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
  5. distanceField: "dist.calculated",
  6. minDistance: 2,
  7. query: { category: "Parks" },
  8. includeLocs: "dist.location",
  9. spherical: true
  10. }
  11. }
  12. ])

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 a2d index on the legacy field.

A document in the places collection resembles the following:

  1. {
  2. "_id" : 3,
  3. "name" : "Polo Grounds",
  4. "location": {
  5. "type" : "Point",
  6. "coordinates" : [ -73.9375, 40.8303 ]
  7. },
  8. "legacy" : [ -73.9375, 40.8303 ],
  9. "category" : "Stadiums"
  10. }

The following example uses the key option to specify that theaggregation should use the location field values for the$geoNear operation rather than the legacy field values.The pipeline also uses $limit to return at most 5 documents.

Note

Starting in version 4.2, MongoDB removes the limit and numoptions for the $geoNear stage as well as the defaultlimit of 100 documents. To limit the results of$geoNear, use the $geoNear stage with the$limit stage.

  1. db.places.aggregate([
  2. {
  3. $geoNear: {
  4. near: { type: "Point", coordinates: [ -73.98142 , 40.71782 ] },
  5. key: "location",
  6. distanceField: "dist.calculated",
  7. query: { "category": "Parks" }
  8. }
  9. },
  10. { $limit: 5 }
  11. ])

The aggregation returns the following:

  1. {
  2. "_id" : 8,
  3. "name" : "Sara D. Roosevelt Park",
  4. "location" : {
  5. "type" : "Point",
  6. "coordinates" : [
  7. -73.9928,
  8. 40.7193
  9. ]
  10. },
  11. "category" : "Parks",
  12. "dist" : {
  13. "calculated" : 974.175764916902
  14. }
  15. }
  16. {
  17. "_id" : 1,
  18. "name" : "Central Park",
  19. "location" : {
  20. "type" : "Point",
  21. "coordinates" : [
  22. -73.97,
  23. 40.77
  24. ]
  25. },
  26. "legacy" : [
  27. -73.97,
  28. 40.77
  29. ],
  30. "category" : "Parks",
  31. "dist" : {
  32. "calculated" : 5887.92792958097
  33. }
  34. }