简体   繁体   中英

Error while executing geo spatial query in MongoDB using Python

I have just started working with Geo Spatial data using MongoDB and Python. Below is my code. For normal queries it works fine but for 'near' query I am getting error.

 from pymongo import MongoClient

client = MongoClient("mongodb+srv://dummyuser:dummypassword@cluster0.xprs.mongodb.net/test?retryWrites=true&w=majority")
db = client["MyDB"]
col = db["MyCollection"]
query = """{
geometry: {
$near: {
$geometry: {
type: 'Point',
coordinates: [77.25467696734609,28.63449787747656]
},
   $maxDistance: 5000,
   $minDistance: 10
  }
 }
}"""

docs = (col.find(query))

for doc in docs:
  print(doc)

While executing this code I am getting below error

C:\user\Python\parse-payment-response\venv\Scripts\python.exe C:/user/Python/jsonParser/mongoclnt.py
Traceback (most recent call last):
  File "C:/user/Python/jsonParser/mongoclnt.py", line 24, in <module>
    docs = [(col.find(query))]
  File "C:\user\Python\parse-payment-response\venv\lib\site-packages\pymongo\collection.py", line 1523, in find
    return Cursor(self, *args, **kwargs)
  File "C:\user\Python\parse-payment-response\venv\lib\site-packages\pymongo\cursor.py", line 144, in __init__
    validate_is_mapping("filter", spec)
  File "C:\user\Python\parse-payment-response\venv\lib\site-packages\pymongo\common.py", line 494, in validate_is_mapping
    raise TypeError("%s must be an instance of dict, bson.son.SON, or "
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

Please help

After lots of effort and search I got this fixed. Code as below:

from pymongo import MongoClient

MongoClient("mongodb+srv://dummyuser:dummypassword@cluster0.xprs.mongodb.net/test?retryWrites=true&w=majority")
db = client["MyDB"]
col = db["MyCollection"]
query={"geometry": {"$nearSphere": {"$geometry": {"type": "Point", "coordinates": [77.25467696734609, 28.63449787747656]}, "$maxDistance": 2000,"$minDistance": 10}}}
docs = col.find(query)
for doc in docs:
  print(doc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM