Geospatial Queries

On this page

MongoDB supports query operations on geospatial data. This section introduces MongoDB’s geospatial features.

Geospatial Data

In MongoDB, you can store geospatial data asGeoJSONobjects or aslegacy coordinate pairs.

GeoJSON Objects

To calculate geometry over an Earth-like sphere, store your location data asGeoJSON objects.

To specify GeoJSON data, use an embedded document with:

  • a field namedtypethat specifies theGeoJSON object typeand

  • a field namedcoordinatesthat specifies the object’s coordinates.

    If specifying latitude and longitude coordinates, list thelongitudefirst and thenlatitude:

    • Valid longitude values are between
      -180
      and
      180
      , both inclusive.
    • Valid latitude values are between
      -90
      and
      90
      (both inclusive).
  1. <
  2. field
  3. >
  4. :
  5. {
  6. type
  7. :
  8. <
  9. GeoJSON
  10. type
  11. >
  12. ,
  13. coordinates
  14. :
  15. <
  16. coordinates
  17. >
  18. }

For example, to specify aGeoJSON Point:

  1. location
  2. :
  3. {
  4. type
  5. :
  6. "Point"
  7. ,
  8. coordinates
  9. :
  10. [
  11. -
  12. 73.856077
  13. ,
  14. 40.848447
  15. ]
  16. }

For a list of the GeoJSON objects supported in MongoDB as well as examples, seeGeoJSON objects.

MongoDB geospatial queries on GeoJSON objects calculate on a sphere; MongoDB uses theWGS84reference system for geospatial queries on GeoJSON objects.

Legacy Coordinate Pairs

To calculate distances on a Euclidean plane, store your location data as legacy coordinate pairs and use a2dindex. MongoDB supports spherical surface calculations on legacy coordinate pairs via a2dsphereindex by converting the data to the GeoJSON Point type.

To specify data as legacy coordinate pairs, you can use either an array (preferred) or an embedded document.

Specify via an array (

Preferred

):

  1. <
  2. field
  3. >
  4. :
  5. [
  6. <
  7. x
  8. >
  9. ,
  10. <
  11. y
  12. >
  13. ]

If specifying latitude and longitude coordinates, list thelongitudefirst and thenlatitude; i.e.

  1. <
  2. field
  3. >
  4. :
  5. [
  6. <
  7. longitude
  8. >
  9. ,
  10. <
  11. latitude
  12. >
  13. ]

If specifying latitude and longitude coordinates, list thelongitudefirst and thenlatitude:

  • Valid longitude values are between
    -180
    and
    180
    , both inclusive.
  • Valid latitude values are between
    -90
    and
    90
    (both inclusive).

Specify via an embedded document:

  1. <
  2. field
  3. >
  4. :
  5. {
  6. <
  7. field1
  8. >
  9. :
  10. <
  11. x
  12. >
  13. ,
  14. <
  15. field2
  16. >
  17. :
  18. <
  19. y
  20. >
  21. }

If specifying latitude and longitude coordinates, the first field, regardless of the field name, must contains thelongitudevalue and the second field, thelatitudevalue ; i.e.

  1. <
  2. field
  3. >
  4. :
  5. {
  6. <
  7. field1
  8. >
  9. :
  10. <
  11. longitude
  12. >
  13. ,
  14. <
  15. field2
  16. >
  17. :
  18. <
  19. latitude
  20. >
  21. }
  • Valid longitude values are between
    -180
    and
    180
    , both inclusive.
  • Valid latitude values are between
    -90
    and
    90
    (both inclusive).

To specify legacy coordinate pairs, arrays are preferred over an embedded document as some languages do not guarantee associative map ordering.

Geospatial Indexes

MongoDB provides the following geospatial index types to support the geospatial queries.

2dsphere

2dsphereindexes support queries that calculategeometries on an earth-like sphere.

To create a2dsphereindex, use thedb.collection.createIndex()method and specify the string literal"2dsphere"as the index type:

  1. db
  2. .
  3. collection
  4. .
  5. createIndex
  6. (
  7. {
  8. <
  9. location
  10. field
  11. >
  12. :
  13. "2dsphere"
  14. }
  15. )

where the<locationfield>is a field whose value is either aGeoJSON objector alegacy coordinates pair.

For more information on the2dsphereindex, see2dsphere Indexes.

2d

2dindexes support queries that calculategeometries on a two-dimensional plane. Although the index can support$nearSpherequeries that calculate on a sphere, if possible, use the2dsphereindex for spherical queries.

To create a2dindex, use thedb.collection.createIndex()method, specifying the location field as the key and the string literal"2d"as the index type:

  1. db
  2. .
  3. collection
  4. .
  5. createIndex
  6. (
  7. {
  8. <
  9. location
  10. field
  11. >
  12. :
  13. "2d"
  14. }
  15. )

where the<locationfield>is a field whose value is alegacy coordinates pair.

For more information on the2dindex, see2d Indexes.

Geospatial Indexes and Sharded Collections

You cannot use a geospatial index as ashard keywhen sharding a collection. However, you can create a geospatial index on a sharded collection by using a different field as the shard key.

For sharded collections, queries using$nearand$nearSphereare not supported. You can instead use either thegeoNearcommand or the$geoNearaggregation stage.

You can also query for geospatial data for a sharded cluster using$geoWithinand$geoIntersect.

Covered Queries

Ageospatial indexescannotcover a query.

Geospatial Queries

NOTE

For spherical queries, use the2dsphereindex result.

The use of2dindex for spherical queries may lead to incorrect results, such as the use of the2dindex for spherical queries that wrap around the poles.

Geospatial Query Operators

MongoDB provides the following geospatial query operators:

NameDescription
$geoIntersectsSelects geometries that intersect with aGeoJSONgeometry. The2dsphereindex supports$geoIntersects.
$geoWithinSelects geometries within a boundingGeoJSON geometry. The2dsphereand2dindexes support$geoWithin.
$nearReturns geospatial objects in proximity to a point. Requires a geospatial index. The2dsphereand2dindexes support$near.
$nearSphereReturns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The2dsphereand2dindexes support$nearSphere.

For more details, including examples, see the individual reference page.

Geospatial Command

MongoDB provides the following geospatial command:

CommandDescription
geoNearPerforms a geospatial query that returns the documents closest to a given point.geoNearrequires ageospatial index.

For more details, including examples, seegeoNearreference page.

Geospatial Aggregation Stage

MongoDB provides the following geospatialaggregation pipeline stage:

StageDescription
$geoNearReturns an ordered stream of documents based on the proximity to a geospatial point. Incorporates the functionality of$match,$sort, and$limitfor geospatial data. The output documents include an additional distance field and can include a location identifier field.$geoNearrequires ageospatial index.

For more details, including examples, see$geoNearreference page.

Geospatial Models

MongoDB geospatial queries can interpret geometry on a flat surface or a sphere.

2dsphereindexes support only spherical queries (i.e. queries that interpret geometries on a spherical surface).

2dindexes support flat queries (i.e. queries that interpret geometries on a flat surface) and some spherical queries. While2dindexes support some spherical queries, the use of2dindexes for these spherical queries can result in error. If possible, use2dsphereindexes for spherical queries.

The following table lists the geospatial query operators, supported query, used by each geospatial operations:

OperationSpherical/Flat QueryNotes
$near(GeoJSONcentroid point in this line and the following line,2dsphereindex)SphericalSee also the$nearSphereoperator, which provides the same functionality when used withGeoJSONand a2dsphereindex.
$near(legacy coordinates,2dindex)Flat
$nearSphere(GeoJSONpoint,2dsphereindex)SphericalProvides the same functionality as$nearoperation that usesGeoJSONpoint and a2dsphereindex.For spherical queries, it may be preferable to use$nearSpherewhich explicitly specifies the spherical queries in the name rather than$nearoperator.
$nearSphere(legacy coordinates,2dindex)SphericalUseGeoJSONpoints instead.
$geoWithin: {$geometry: … }Spherical
$geoWithin: {$box: … }Flat
$geoWithin: {$polygon: … }Flat
$geoWithin: {$center: … }Flat
$geoWithin: {$centerSphere: … }Spherical
$geoIntersectsSpherical
geoNear(2dsphereindex)Spherical
geoNear(2dindex)Flat
$geoNear(2dsphereindex)Spherical
$geoNear(2dindex)Flat

Example

Create a collectionplaceswith the following documents:

  1. db
  2. .
  3. places
  4. .
  5. insert
  6. (
  7. {
  8. name
  9. :
  10. "Central Park"
  11. ,
  12. location
  13. :
  14. {
  15. type
  16. :
  17. "Point"
  18. ,
  19. coordinates
  20. :
  21. [
  22. -
  23. 73.97
  24. ,
  25. 40.77
  26. ]
  27. },
  28. category
  29. :
  30. "Parks"
  31. }
  32. );
  33. db
  34. .
  35. places
  36. .
  37. insert
  38. (
  39. {
  40. name
  41. :
  42. "Sara D. Roosevelt Park"
  43. ,
  44. location
  45. :
  46. {
  47. type
  48. :
  49. "Point"
  50. ,
  51. coordinates
  52. :
  53. [
  54. -
  55. 73.9928
  56. ,
  57. 40.7193
  58. ]
  59. },
  60. category
  61. :
  62. "Parks"
  63. }
  64. );
  65. db
  66. .
  67. places
  68. .
  69. insert
  70. (
  71. {
  72. name
  73. :
  74. "Polo Grounds"
  75. ,
  76. location
  77. :
  78. {
  79. type
  80. :
  81. "Point"
  82. ,
  83. coordinates
  84. :
  85. [
  86. -
  87. 73.9375
  88. ,
  89. 40.8303
  90. ]
  91. },
  92. category
  93. :
  94. "Stadiums"
  95. }
  96. );

The following operation creates a2dsphereindex on thelocationfield:

  1. db
  2. .
  3. places
  4. .
  5. createIndex
  6. (
  7. {
  8. location
  9. :
  10. "2dsphere"
  11. }
  12. )

The following query uses the$nearoperator to return documents that are at least 1000 meters from and at most 5000 meters from the specified GeoJSON point, sorted in order from nearest to farthest:

  1. db
  2. .
  3. places
  4. .
  5. find
  6. (
  7. {
  8. location
  9. :
  10. {
  11. $near
  12. :
  13. {
  14. $geometry
  15. :
  16. {
  17. type
  18. :
  19. "Point"
  20. ,
  21. coordinates
  22. :
  23. [
  24. -
  25. 73.9667
  26. ,
  27. 40.78
  28. ]
  29. },
  30. $minDistance
  31. :
  32. 1000
  33. ,
  34. $maxDistance
  35. :
  36. 5000
  37. }
  38. }
  39. }
  40. )

The following operation uses thegeoNearcommand to return documents that match the query filter{category:"Parks"}, sorted in order of nearest to farthest to the specified GeoJSON point:

  1. db
  2. .
  3. runCommand
  4. (
  5. {
  6. geoNear
  7. :
  8. "places"
  9. ,
  10. near
  11. :
  12. {
  13. type
  14. :
  15. "Point"
  16. ,
  17. coordinates
  18. :
  19. [
  20. -
  21. 73.9667
  22. ,
  23. 40.78
  24. ]
  25. },
  26. spherical
  27. :
  28. true
  29. ,
  30. query
  31. :
  32. {
  33. category
  34. :
  35. "Parks"
  36. }
  37. }
  38. )