Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 70 ยท Indexes and performance

Geospatial Data and Queries

Store locations as GeoJSON, create a 2dsphere index, and query with $near, $geoWithin, $geoIntersects and the $geoNear stage to find places nearby, inside an area or crossing a route.

"Which restaurants are within 500 meters?" "Is this delivery address inside our service area?" "Which bus routes cross this neighborhood?" Questions about where things are come up in almost every app that has a map, and MongoDB answers them natively. You store locations in a standard format, add a special index, and query with a handful of operators that understand distance on the surface of the Earth.

This lesson covers GeoJSON, the 2dsphere and legacy 2d indexes, the operators $near, $geoWithin and $geoIntersects, and the $geoNear aggregation stage. The snippets in plain code blocks are real mongosh syntax and cannot run here. The TryIts are plain JavaScript stand-ins that compute the same distances and containment tests with real geometry (the haversine formula and a point-in-polygon test), so you can check your intuition. They do not use an index and are not a MongoDB server.

Storing locations: GeoJSON

MongoDB expects location data in GeoJSON, a JSON format with a type and coordinates. The most common shapes are:

JavaScript
{ type: "Point", coordinates: [13.405, 52.52] }                        // one place
{ type: "LineString", coordinates: [[13.40, 52.52], [13.43, 52.51]] }  // a route
{ type: "Polygon", coordinates: [[[13.0, 52.0], [14.0, 52.0], [14.0, 53.0], [13.0, 53.0], [13.0, 52.0]]] }

Two rules trip up nearly everyone:

  1. Longitude comes first, then latitude: [lng, lat], the opposite of how people say "latitude, longitude". Berlin is [13.405, 52.52], not [52.52, 13.405]. Swapping them silently places your data in the wrong part of the world (or fails if latitude falls outside -90 to 90).
  2. A polygon ring must be closed: the first and last position are identical. The outer ring comes first; any holes follow as extra rings. Use the right-hand rule for a standard ring (counter-clockwise outer ring).

A location lives in an ordinary field of an ordinary document:

JavaScript
db.places.insertMany([
  { name: "Central Cafe",  category: "cafe",  location: { type: "Point", coordinates: [13.4050, 52.5200] } },
  { name: "River Bakery",  category: "bakery", location: { type: "Point", coordinates: [13.4130, 52.5230] } },
  { name: "Station Kiosk", category: "kiosk", location: { type: "Point", coordinates: [13.3690, 52.5250] } }
])

The 2dsphere index

Geospatial operators such as $near need a geospatial index. For GeoJSON data on a sphere, create a 2dsphere index:

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

It works like any other index, and it can be part of a compound index such as { category: 1, location: "2dsphere" }, which lets one query filter by category and by distance together. A 2dsphere index uses spherical geometry, so distances account for the curvature of the Earth and are in meters.

The older 2d index is for flat, legacy coordinate pairs ([x, y] or { lng, lat } stored as a plain array) and treats the world as a plane, with distances in the units of your coordinates. Use it only for non-geographic grids, such as a game map. For anything on Earth use GeoJSON with 2dsphere.

Finding what is nearby: $near

$near returns documents ordered from nearest to farthest, optionally within a distance range:

JavaScript
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [13.4000, 52.5200] },
      $maxDistance: 1000,   // meters
      $minDistance: 50      // meters, optional
    }
  }
})

Because the results come back already sorted by distance, you do not need sort(), and in fact $near ignores any other sort order you request on the field. Combine it with other filters (category: "cafe") and limit(10) for "the ten nearest cafes". $nearSphere is the same idea for legacy coordinates on a sphere. Note that $near requires a geospatial index; without one the query fails.

The first TryIt stores five places and runs a $near query with a stand-in that computes real great-circle distances.

JS $near: nearest first, within a distance

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the pattern: the same sorted list answers all four questions once you add a distance filter, a category filter or a limit. A real server uses the 2dsphere index to avoid computing the distance for every place.

Searching inside an area: $geoWithin

$geoWithin returns documents whose location is entirely inside a shape. It does not sort the results and does not require an index, although an index makes it faster. You can give it a GeoJSON polygon (or multipolygon), or a legacy shape:

JavaScript
// Inside a polygon (for example a delivery zone)
db.places.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [[[13.38, 52.50], [13.43, 52.50], [13.43, 52.54], [13.38, 52.54], [13.38, 52.50]]]
      }
    }
  }
})

// Inside a circle on the sphere: radius in RADIANS = distance / Earth radius (6378.1 km)
db.places.find({
  location: { $geoWithin: { $centerSphere: [[13.40, 52.52], 1 / 6378.1] } }   // about 1 km
})

$centerSphere takes its radius in radians, which is the second thing to remember. To convert, divide the distance in kilometers by 6378.1 (or miles by 3963.2). The legacy shapes $box, $center and $polygon work in planar coordinates and belong to the 2d index.

Crossing shapes: $geoIntersects

$geoIntersects matches documents whose geometry intersects the shape you provide. It is the right tool when your stored data is itself a line or area: "which delivery zones contain this address?" or "which routes pass through this district?"

JavaScript
// zones: { name, area: { type: "Polygon", ... } } with a 2dsphere index on area
db.zones.find({
  area: {
    $geoIntersects: { $geometry: { type: "Point", coordinates: [13.405, 52.52] } }
  }
})

With a Point as the query shape, this answers "which stored areas contain this point?" With a LineString, it finds the areas the line passes through.

The $geoNear aggregation stage

In an aggregation pipeline, the $geoNear stage does what $near does and also returns the distance as a field. It must be the first stage in the pipeline and needs a geospatial index:

JavaScript
db.places.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [13.4, 52.52] },
      distanceField: "distanceMeters",
      maxDistance: 3000,
      query: { category: "cafe" },
      spherical: true
    }
  },
  { $project: { _id: 0, name: 1, distanceMeters: { $round: ["$distanceMeters", 0] } } },
  { $limit: 5 }
])

If the collection has more than one geospatial index you must name the one to use with the key option. Use $geoNear when you need the distance in the output or further stages after the search. $near is a query operator for find; it is not allowed inside an aggregation $match, which is exactly the gap $geoNear fills.

The second TryIt tests containment: a point-in-polygon check for $geoWithin and $geoIntersects, and the radians conversion for $centerSphere.

JS $geoWithin, $geoIntersects and $centerSphere

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three points show the three possible answers to a $geoIntersects query: one zone, a different zone, or none. A real server evaluates this with spherical geometry and the index; the flat test used here is accurate enough for small areas.

Practical tips

  • Always store [longitude, latitude] and validate ranges (-180 to 180 and -90 to 90) at write time with schema validation.
  • Create the index before you rely on $near or $geoNear, and check with explain that the query uses it (a GEO_NEAR_2DSPHERE stage).
  • Put the equality filter first in a compound index ({ category: 1, location: "2dsphere" }) when most queries filter by category too.
  • For "within a radius" without sorting, $geoWithin with $centerSphere is the cheaper choice; for "nearest N", use $near or $geoNear with limit.
  • Distances in a 2dsphere query are in meters; in a 2d index they are in the units of your coordinates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In GeoJSON, which order do coordinates use?

    GeoJSON and MongoDB use [longitude, latitude]. Swapping them places the point in the wrong location or fails validation.
  2. 2. Which operator returns documents sorted from nearest to farthest?

    $near (and $nearSphere, and the $geoNear stage) return results ordered by distance. $geoWithin does not sort.
  3. 3. What unit does the radius of $centerSphere use?

    $centerSphere takes radians. Divide kilometers by 6378.1 to convert.
  4. 4. Which statement about $geoNear is true?

    $geoNear must come first, needs a geospatial index, and writes the computed distance to distanceField.
  5. 5. Which index do you create for GeoJSON points on the Earth?

    A 2dsphere index understands spherical geometry. The 2d index is for flat legacy coordinates.

Summary

  • Store places as GeoJSON with [longitude, latitude], and close every polygon ring.
  • Create a 2dsphere index for GeoJSON on the Earth; use 2d only for flat, legacy coordinate pairs.
  • $near and $geoNear return nearest-first results with $maxDistance/maxDistance in meters; $geoNear is a first pipeline stage that also returns the distance.
  • $geoWithin finds documents inside a shape (a polygon, or a $centerSphere with a radius in radians); $geoIntersects matches stored shapes that touch your shape.
  • Combine geo fields with other fields in a compound index, and confirm the plan with explain.

Next, look at another family of query operators in Bitwise Query Operators.