Question

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. 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. 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?

Was it helpful?

Solution

Yes you can. You can do this with custom javascript function provided in search. Note that you have to write your between in javascript.

Check into $where clause in mongo, but remember that it will do a whole scan of the collection.

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.

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. With coordinates from your document - you have to do something like this.location[0], this.location[1]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top