0
0
MongodbHow-ToBeginner · 4 min read

How to Use $near in MongoDB for Geospatial Queries

Use the $near operator in MongoDB to find documents with geospatial data close to a specified point. It requires a geospatial index and a query with coordinates inside $near to return results sorted by proximity.
📐

Syntax

The $near operator is used inside a find() query to search for documents with location data near a given point. It requires a geospatial index on the location field.

Basic syntax:

{ locationField: { $near: { $geometry: { type: "Point", coordinates: [ ,  ] }, $maxDistance: , $minDistance:  } } }

Explanation:

  • locationField: The field with geospatial data.
  • $geometry: Defines the point to search near.
  • coordinates: Array with longitude and latitude.
  • $maxDistance: Optional max distance in meters.
  • $minDistance: Optional min distance in meters.
json
{
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [ <longitude>, <latitude> ]
      },
      $maxDistance: <distance_in_meters>,
      $minDistance: <distance_in_meters>
    }
  }
}
💻

Example

This example shows how to find places near a specific point within 5000 meters. It assumes a collection places with a location field indexed as a 2dsphere.

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

// Insert sample documents
 db.places.insertMany([
   { name: "Coffee Shop", location: { type: "Point", coordinates: [ -73.97, 40.77 ] } },
   { name: "Library", location: { type: "Point", coordinates: [ -73.98, 40.78 ] } },
   { name: "Bookstore", location: { type: "Point", coordinates: [ -74.00, 40.75 ] } }
 ])

// Query to find places near a point
 db.places.find({
   location: {
     $near: {
       $geometry: {
         type: "Point",
         coordinates: [ -73.97, 40.77 ]
       },
       $maxDistance: 5000
     }
   }
})
Output
[ { "_id": ObjectId("..."), "name": "Coffee Shop", "location": { "type": "Point", "coordinates": [ -73.97, 40.77 ] } }, { "_id": ObjectId("..."), "name": "Library", "location": { "type": "Point", "coordinates": [ -73.98, 40.78 ] } }, { "_id": ObjectId("..."), "name": "Bookstore", "location": { "type": "Point", "coordinates": [ -74.00, 40.75 ] } } ]
⚠️

Common Pitfalls

  • No geospatial index: The $near operator requires a 2dsphere index on the location field; without it, the query will fail.
  • Wrong coordinate order: Coordinates must be in [longitude, latitude] order, not the other way around.
  • Using $near with non-Point geometry: $near works only with Point geometry, not polygons or lines.
  • Ignoring units: Distances for $maxDistance and $minDistance are in meters for 2dsphere indexes.
mongodb
/* Wrong: No index created */
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [ -73.97, 40.77 ] },
      $maxDistance: 1000
    }
  }
})

/* Right: Create 2dsphere index first */
db.places.createIndex({ location: "2dsphere" })
📊

Quick Reference

  • $near: Finds documents near a point.
  • $geometry: Defines the point with type and coordinates.
  • Coordinates: Must be [longitude, latitude].
  • $maxDistance: Optional max distance in meters.
  • $minDistance: Optional min distance in meters.
  • Index: Requires 2dsphere index on the location field.

Key Takeaways

Always create a 2dsphere index on the location field before using $near.
Use [longitude, latitude] order for coordinates in $near queries.
$near returns documents sorted by distance from the specified point.
$maxDistance and $minDistance are optional and measured in meters.
$near only works with Point geometry type in geospatial queries.