简体   繁体   English

具有谓词功能的PyMongo查询

[英]PyMongo Queries with a Predicate Function

I have a series of posts stored in my database like this: 我在数据库中存储了一系列帖子,如下所示:

{
    content: 'foo',
    location: (37.423021, -122.083739)
},
{
    content: 'bar',
    location: (37.422473, -122.090386)
}

I also have a function between which can calculate the distance, in miles, between two points. 我还有一个函数,可以计算两点between的距离(以英里为单位)。 It works as follows: 其工作方式如下:

>>> between((37.423021, -122.083739), (37.422473, -122.090386))
0.36649505427211615

I'm using this to build a predicate function valid that would take in the document and return a boolean signifying whether or not it is valid. 我正在使用它来构建一个valid的谓词函数,该谓词函数将接收到文档中并返回一个布尔值,表示它是否有效。 The function would likely look something like: 该函数可能类似于:

def valid(document):
    return between(document.location, CONSTANT_LOCATION)

Is it possible to use this predicate as the selector for the query? 是否可以将此谓词用作查询的选择器?

Yes you can. 是的你可以。 You can do this with custom javascript function provided in search. 您可以使用搜索中提供的自定义javascript函数来执行此操作。 Note that you have to write your between in javascript. 请注意,您必须使用javascript编写两者之间的内容。

Check into $where clause in mongo, but remember that it will do a whole scan of the collection. 在mongo中检查$ where子句,但请记住它将对集合进行完整扫描。

db.myCollection.find({ $where: function() {
   return (between((37.423021, -122.083739), (37.422473, -122.090386)) < 1);
}});

If you calculate the distance between 2 points using haversine take a look at my optimized formula here. 如果您使用Haversine计算2个点之间的距离,请在此处查看我的优化公式

One thing I can not understand is: how do you get the first point and the second. 我无法理解的一件事是:如何获得第一点和第二点。 It looks like they are in the different documents. 看起来它们在不同的文档中。

Edit than you will have no problems with the method, I provided. 编辑比你将与方法没有问题,我公司提供。 You can either write your function inside of return, or try to save your function (it was already explained somewhere on SO how to do this) and invoke it in the way I showed. 您可以在return内部编写函数,也可以尝试保存函数(在SO的某处已对此进行了说明)如何按照我演示的方式调用它。 With coordinates from your document - you have to do something like this.location[0] , this.location[1] 使用文档中的坐标-您必须执行以下操作: this.location[0]this.location[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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