===== $near ===== .. default-domain:: mongodb .. contents:: On this page :local: :backlinks: none :depth: 1 :class: singlecol .. query:: $near .. versionchanged:: 2.4 Specifies a point for which a :term:`geospatial` query returns the closest documents first. The query sorts the documents from nearest to farthest. The :query:`$near` operator can query for a :term:`GeoJSON` point or for a point defined by legacy coordinate pairs. The optional :query:`$maxDistance` operator limits a :query:`$near` query to return only those documents that fall within a maximum distance of a point. If you query for a GeoJSON point, specify :query:`$maxDistance` in meters. If you query for legacy coordinate pairs, specify :query:`$maxDistance` in radians. The :query:`$near` operator requires a geospatial index: a ``2dsphere`` index for GeoJSON points; a ``2d`` index for legacy coordinate pairs. By default, queries that use a ``2d`` index return a limit of 100 documents; however you may use :method:`~cursor.limit()` to change the number of results. .. TODO remove the following "include" statement in 2.6 .. note:: You cannot combine the :query:`$near` operator, which requires a special :ref:`geospatial index `, with a query operator or command that uses a different type of special index. For example you cannot combine :query:`$near` with the :dbcommand:`text` command. For queries on GeoJSON data, use the following syntax: .. code-block:: javascript db..find( { : { $near : { $geometry : { type : "Point" , coordinates : [ , ] }, $maxDistance : } } } ) .. important:: Specify coordinates in this order: **"longitude, latitude."** The following example selects the documents with coordinates nearest to ``[ 40 , 5 ]`` and limits the maximum distance to 500 meters from the specified GeoJSON point: .. code-block:: javascript db.places.find( { loc: { $near : { $geometry : { type : "Point" , coordinates: [ 40 , 5 ] }, $maxDistance : 500 } } } ) For queries on legacy coordinate pairs, use the following syntax: .. code-block:: javascript db..find( { : { $near : [ , ] , $maxDistance: } } ) .. important:: If you use longitude and latitude, specify **longitude first**. The following example query returns documents with location values that are 10 or fewer units from the point ``[ 40 , 5 ]``. For GeoJSON point object, specify the $maxDistance in meters, not radians. .. code-block:: javascript db.places.find( { loc : { $near : [ 40 , 5 ] , $maxDistance : 10 } } ) .. note:: You can further limit the number of results using :method:`cursor.limit()`. Specifying a batch size (i.e. :method:`batchSize() `) in conjunction with queries that use the :query:`$near` is not defined. See :issue:`SERVER-5236` for more information.