Search Geographic Nearest Neighbor Data (MongoDB)

Hello. This is an example of a function that searches the nearest neighbor data from a given point using MongoDB + Python (pymongo) (assuming `` `2dsphere``` indexing).

$maxdistanceAlso given, and if nothing is searched, definedno_dataI tried to return. Changed to use the recommended api[^1]。

[^ 1]: In this example, if you use `$ geoNear```, .count () ``, it is currently deprecated. You can also refer to "MongoDB Geographical Spatial Index Query Organization".

NO_DATA = {}
def 2dsphere_near():
  point = [135.0, 35.0]
  query = {"loc": {"$nearSphere": {
           "$geometry": {"type": "Point", "coordinates": point},
           "$maxDistance": 1000}}}  # in meter
  for nearest_data in mycollection.find(query).limit(1):
    return nearest_data
  return NO_DATA

Recommended Posts

Search Geographic Nearest Neighbor Data (MongoDB)
Approximate Nearest Neighbor Search for Similar Image Analysis (For Beginners) (1)