问题描述
我正在尝试编写脚本来执行此处提到的基本2dsphere索引操作使用pymongo 2dsphere .
I'm trying to code up a script to do basic 2dsphere index operation mentioned here2dsphere using pymongo.
我找不到任何示例可以弄清楚,这是我到目前为止的尝试:
I could not find any example to figure it out, this is my attempt so far:
from pymongo import GEOSPHERE
client=MongoClient('localhost',27017)
db=client['dbtest']
points=db['points']
points.create_index([("loc",GEOSPHERE)])
points.insert({"loc":[2 5]})
points.insert({"loc":[30,5]})
more points.insert
for doc in points.find({"loc" : {"$near": { "$geometry" : {"type":"Point","coordinates":[1,2]},"$maxDistance":20}}}):
print doc
它给出错误pymongo.errors.OperationFailure: database error: can't find special index: 2d for: { loc: { $near: { $geometry: { type: "Point", coordinates: [ 1, 2 ] }, $maxDistance: 20 } } }
推荐答案
2dsphere (pymongo.GEOSPHERE)索引类型仅在MongoDB 2.4及更高版本中有效.您还将要使用 GeoJSON 格式你的观点.最后,MongoDB的地理查询运算符是顺序敏感的,因此您必须使用 SON 使用$ maxDistance之类的选项时.这是使用 $ near
The 2dsphere (pymongo.GEOSPHERE) index type only works in MongoDB 2.4 and newer. You're also going to want to use GeoJSON format for your points. Finally, MongoDB's geo query operators are order sensitive, so you'll have to use SON when using options like $maxDistance. Here's an example using $near:
>>> c = pymongo.MongoClient()
>>> points = c.dbtest.points
>>> points.ensure_index([("loc", pymongo.GEOSPHERE)])
u'loc_2dsphere'
>>> points.insert({'loc': {'type': 'Point', 'coordinates': [40, 5]}})
ObjectId('51b0e508fba522160ce84c3a')
>>> for doc in points.find({"loc" : SON([("$near", { "$geometry" : SON([("type", "Point"), ("coordinates", [40, 5])])}), ("$maxDistance", 10)])}):
... doc
...
{u'loc': {u'type': u'Point', u'coordinates': [40, 5]}, u'_id': ObjectId('51b0e508fba522160ce84c3a')}
这篇关于有谁知道pymongo中2dsphere索引的工作示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!