Geospatial Queries

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

Geospatial Data

In MongoDB, you can store geospatial data as GeoJSON objects or as legacy coordinate pairs.

GeoJSON Objects

To calculate geometry over an Earth-like sphere, store your locationdata as GeoJSON objects.

To specify GeoJSON data, use an embedded document with:

  • a field named type that specifies the GeoJSON objecttype and

  • a field named coordinates that specifies the object’scoordinates.

If specifying latitude and longitude coordinates, list thelongitude first and then latitude:

  • Valid longitude values are between -180 and 180, bothinclusive.
  • Valid latitude values are between -90 and 90, bothinclusive.
  1. <field>: { type: <GeoJSON type> , coordinates: <coordinates> }

For example, to specify a GeoJSON Point:

  1. location: {
  2. type: "Point",
  3. coordinates: [-73.856077, 40.848447]
  4. }

For a list of the GeoJSON objects supported in MongoDB as well asexamples, see GeoJSON objects.

MongoDB geospatial queries on GeoJSON objects calculate on a sphere;MongoDB uses the WGS84 reference system for geospatialqueries on GeoJSON objects.

Legacy Coordinate Pairs

To calculate distances on a Euclidean plane, store your location dataas legacy coordinate pairs and use a 2d index. MongoDBsupports spherical surface calculations on legacy coordinate pairs viaa 2dsphere index by converting the data to the GeoJSON Pointtype.

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

  • Specify via an array (Preferred):
  1. <field>: [ <x>, <y> ]

If specifying latitude and longitude coordinates, list thelongitude first and then latitude; i.e.

  1. <field>: [<longitude>, <latitude> ]
  • Valid longitude values are between -180 and 180, bothinclusive.
  • Valid latitude values are between -90 and 90, bothinclusive.
    • Specify via an embedded document:
  1. <field>: { <field1>: <x>, <field2>: <y> }

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

  1. <field>: { <field1>: <longitude>, <field2>: <latitude> }
  • Valid longitude values are between -180 and 180, bothinclusive.
  • Valid latitude values are between -90 and 90, bothinclusive.

To specify legacy coordinate pairs, arrays are preferred over anembedded document as some languages do not guarantee associative mapordering.

Geospatial Indexes

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

2dsphere

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

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

  1. db.collection.createIndex( { <location field> : "2dsphere" } )

where the <location field> is a field whose value is either aGeoJSON object or a legacycoordinates pair.

For more information on the 2dsphere index, see2dsphere Indexes.

2d

2d indexes support queries that calculategeometries on a two-dimensional plane.Although the index can support $nearSphere queries thatcalculate on a sphere, if possible, use the 2dsphere indexfor spherical queries.

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

  1. db.collection.createIndex( { <location field> : "2d" } )

where the <location field> is a field whose value is a legacycoordinates pair.

For more information on the 2d index, see 2d Indexes.

Geospatial Indexes and Sharded Collections

You cannot use a geospatial index as a shard key when sharding acollection. However, you can create a geospatial indexon a sharded collection by using a different field as the shard key.

The following geospatial operations are supported on shardedcollections:

Starting in MongoDB 4.0, $near and $nearSphere queries are supported forsharded collections.

In earlier MongoDB versions, $near and $nearSphere queries are not supportedfor sharded collections; instead, for sharded clusters, you must usethe $geoNear aggregation stage or the geoNear command(available in MongoDB 4.0 and earlier).

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

Covered Queries

Geospatial indexes cannotcover a query.

Geospatial Queries

Note

For spherical queries, use the 2dsphere index result.

The use of 2d index for spherical queries may lead to incorrectresults, such as the use of the 2d index for spherical queriesthat wrap around the poles.

Geospatial Query Operators

MongoDB provides the following geospatial query operators:

NameDescription
$geoIntersectsSelects geometries that intersect with a GeoJSON geometry.The 2dsphere index supports$geoIntersects.
$geoWithinSelects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support$geoWithin.
$nearReturns geospatial objects in proximity to a point.Requires a geospatial index. The 2dsphere and 2d indexes support$near.
$nearSphereReturns geospatial objects in proximity to a point on a sphere.Requires a geospatial index. The 2dsphere and 2d indexes support$nearSphere.

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

Geospatial Aggregation Stage

MongoDB provides the following geospatial aggregation pipelinestage:

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

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

Geospatial Models

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

2dsphere indexes support only spherical queries (i.e. queries thatinterpret geometries on a spherical surface).

2d indexes support flat queries (i.e. queries that interpretgeometries on a flat surface) and some spherical queries. While 2dindexes support some spherical queries, the use of 2d indexes forthese spherical queries can result in error. If possible, use2dsphere indexes for spherical queries.

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

OperationSpherical/Flat QueryNotes
$near (GeoJSON centroidpoint in this line and the following line, 2dsphere index)SphericalSee also the $nearSphere operator, which provides thesame functionality when used with GeoJSON and a 2dsphere index.
$near (legacy coordinates, 2d index)Flat
$nearSphere (GeoJSON point, 2dsphere index)SphericalProvides the same functionality as $near operation thatuses GeoJSON point and a2dsphere index.For spherical queries, it may be preferable to use$nearSphere which explicitly specifies the sphericalqueries in the name rather than $near operator.
$nearSphere (legacy coordinates, 2d index)SphericalUse GeoJSON points instead.
$geoWithin : { $geometry: … }Spherical
$geoWithin : { $box: … }Flat
$geoWithin : { $polygon: … }Flat
$geoWithin : { $center: … }Flat
$geoWithin : { $centerSphere: … }Spherical
$geoIntersectsSpherical
$geoNear aggregation stage (2dsphere index)Spherical
$geoNear aggregation stage (2d index)Flat

Example

Create a collection places with the following documents:

  1. db.places.insert( {
  2. name: "Central Park",
  3. location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
  4. category: "Parks"
  5. } );
  6. db.places.insert( {
  7. name: "Sara D. Roosevelt Park",
  8. location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
  9. category: "Parks"
  10. } );
  11. db.places.insert( {
  12. name: "Polo Grounds",
  13. location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] },
  14. category: "Stadiums"
  15. } );

The following operation creates a 2dsphere index on thelocation field:

  1. db.places.createIndex( { location: "2dsphere" } )

The following query uses the $near operator to returndocuments that are at least 1000 meters from and at most 5000 metersfrom the specified GeoJSON point, sorted in order from nearest tofarthest:

  1. db.places.find(
  2. {
  3. location:
  4. { $near:
  5. {
  6. $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
  7. $minDistance: 1000,
  8. $maxDistance: 5000
  9. }
  10. }
  11. }
  12. )

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

  1. db.places.aggregate( [
  2. {
  3. $geoNear: {
  4. near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
  5. spherical: true,
  6. query: { category: "Parks" },
  7. distanceField: "calcDistance"
  8. }
  9. }
  10. ] )