Imagine that you have a collection with the following structure:
{
"_id": ObjectId("543f1ec50204444c53ba39a0"),
"request_ip": "61.111.36.11",
"owner": ObjectId("543f227c0204444c53ba4b28"),
"loc": [-116.199, 43.6186]
}
Where loc
contains the location of a geographical point defined by its latitude and longitude respectively.
Well, what you need is to find the documents in the collection based on the distance calculated between your locations and another given point.
In this case, the aggregate ()
function is used:
cercanos = collection.aggregate(
[{
"$geoNear": {
"near": [ 52.15077 , 9.95112 ],
"distanceField": "dist",
"spherical": True,
"limit":2
}
}])
When you follow the MongoDB documentation (https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear) everything seems to be in order, however when you run several errors appear:
Traceback (most recent call last):
File "E:\Documents\EclipseProjects\Bonus8\src\pru.py", line 154, in <module>
"spherical": True,
File "D:\Python\lib\site-packages\pymongo\collection.py", line 1870, in aggregate
collation=collation)
File "D:\Python\lib\site-packages\pymongo\collection.py", line 232, in _command
collation=collation)
File "D:\Python\lib\site-packages\pymongo\pool.py", line 419, in command
collation=collation)
File "D:\Python\lib\site-packages\pymongo\network.py", line 116, in command
parse_write_concern_error=parse_write_concern_error)
File "D:\Python\lib\site-packages\pymongo\helpers.py", line 210, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: geoNear command failed: { ok: 0.0, errmsg: "no geo indices for geoNear" }
$geoNear
Quoting from the manual page: "The collection must have a geospatial index." Which again also has a nice link to the other manual page describing the indexes themselves. Nothing "shell specific" about it. – Neil Lunn