Navigation

geoSearch

On this page

geoSearch

The geoSearch command provides an interface to MongoDB’s haystack index functionality. These indexes are useful for returning results based on location coordinates after collecting results based on some other query (i.e. a “haystack.”)

The geoSearch command accepts a document that contains the following fields.

Field Type Description
geoSearch string The collection to query.
search document Query to filter documents.
near array Coordinates of a point.
maxDistance number Optional. Maximum distance from the specified point.
limit number Optional. Maximum number of documents to return.
readConcern document

Optional. Specifies the read concern. The option has the following syntax:

readConcern: { level: <value> }

Possible read concern values are:

For more formation on the read concern levels, see Read Concern Levels.

For more information on the read concern levels, see Read Concern Levels.

txnNumber 64-bit integer/long

Optional.

A strictly increasing non-negative number that uniquely identifies the command in the command’s session.

If specified, the command must also include the lsid option.

New in version 3.6.

lsid document

Optional.

The document that specifies the unique id of the session associated with the command. If the txnNumber is specified, the lsid is required.

Tip

The mongo shell and the drivers provide helpers to start the session and set the lsid for the commands.

New in version 3.6.

Behavior

Unless specified otherwise, the geoSearch command limits results to 50 documents.

Important

geoSearch is not supported for sharded clusters.

Examples

Consider the following example:

db.runCommand({
   geoSearch : "places",
   near: [ -73.9667, 40.78 ],
   maxDistance : 6,
   search : { type : "restaurant" },
   limit : 30
})

The above command returns all documents with a type of restaurant having a maximum distance of 6 units from the coordinates [ -73.9667, 40.78 ] in the collection places up to a maximum of 30 results.

Override Default Read Concern

To override the default read concern level of "local", use the readConcern option.

The following operation on a replica set specifies a Read Concern of "majority" to read the most recent copy of the data confirmed as having been written to a majority of the nodes.

Note

db.runCommand(
   {
      geoSearch: "places",
      near: [ -73.9667, 40.78 ],
      search : { type : "restaurant" },
      readConcern: { level: "majority" }
    }
)

To ensure that a single thread can read its own writes, use "majority" read concern and "majority" write concern against the primary of the replica set.