您好我使用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>
答案 0 :(得分:1)
这更像是一个提示,但是:
MongoDB中的 $near
运算符有两个子句:$geometry
和$maxDistance
(这就是你在Mongo shell中调用它的方式)。但看起来您的自定义对象尝试仅使用$near
实例化$geometry
子句作为参数。
所以它不是tracks__location__max_distance
,而是tracks__location__near__max_distance
之类的东西(即max_distance应该在$near
子句内。)