こんにちは。
MongoDB + Python (pymongo) 利用で、与点からの最近傍データを検索する関数例です(2dsphere
インデックス付与を仮定)。
$maxDistance
も与えており、また何も検索されなかった場合には、定義しておいた NO_DATA
を返すようにしました。推奨の API を用いるようにしました 1。
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
-
今回例では、
$geoNear
、.count()
をもしも使用すると現在は非推奨だそうです。なお「MongoDBの地理空間インデックス・クエリ整理」も参考になります。 ↩