来自mongoengine max_distance查询的数据库错误

时间:2014-08-16 17:29:45

标签: python django pymongo mongoengine

您好我使用mongoengine查询数据有问题。我尝试像在文档中那样做,但我有一个问题。

我创建了两个模型

class Alarm(mongoengine.Document):
    added = mongoengine.DateTimeField()
    title = mongoengine.StringField()
    tracks = mongoengine.ListField(mongoengine.EmbeddedDocumentField(Track))

    meta = {
        'indexes': [[("tracks.location", "2dsphere")]]
    }

class Track(mongoengine.EmbeddedDocument):
    created_on = mongoengine.DateTimeField()
    location = mongoengine.PointField()

从django shell我添加一行:

db.alarm.insert({"title": "Warszawa", "tracks": [{"location": {"type": "Point", "coordinates": [21.01666, 52.233333]}}]})

我连接到mongodb并从shell中尝试使用$ near:

找到我的新位置
>db.alarm.find({'tracks.location': {$near: {$geometry: {"type": "Point", coordinates: [18.068611, 59.329444]}, $maxDistance: 810997}}})
>


> db.alarm.find({'tracks.location': {$near: {$geometry: {"type": "Point", coordinates: [18.068611, 59.329444]}, $maxDistance: 810998}}})
{
 "_id" : ObjectId("53ef89626dda06655a57a342"), "title" : "Warszawa",
"tracks" : [ { "location" : { "type" : "Point", "coordinates" : [
21.01666, 52.233333 ] } } ] }

返回的结果是我的预期。第一个查询返回没有秒找到我的位置。

但是使用mongoengine

我无法收到相同的结果
Alarm.objects(tracks__location__near = {"coordinates":[ 21.01666, 52.233333 ] , "type": "Point"}, tracks__location__max_distance=810998)

我得到:

<repr(<mongoengine.queryset.queryset.QuerySet at 0x7ff3a50e8a10>) failed: pymongo.errors.OperationFailure: database error: Can't canonicalize query: BadValue geo near accepts just one argument when querying for a GeoJSON point. Extra field found: $maxDistance: 810998>

1 个答案:

答案 0 :(得分:1)

这更像是一个提示,但是:

MongoDB中的

$near运算符有两个子句:$geometry$maxDistance(这就是你在Mongo shell中调用它的方式)。但看起来您的自定义对象尝试仅使用$near实例化$geometry子句作为参数。

所以它不是tracks__location__max_distance,而是tracks__location__near__max_distance之类的东西(即max_distance应该在$near子句内。)