0

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?

Ankit Ranjan
  • 114
  • 12

1 Answers1

1

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]

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • To clarify, the first point is hardcoded into the function. The second should be an attribute of the document queried. – Ankit Ranjan Mar 29 '14 at 21:54
  • Is it possible to use a Python function as the `$where` clause? – Ankit Ranjan Mar 29 '14 at 22:11
  • @AnkitRanjan no. You are inside of mongo environment (think you are inside of mysql). Mongo accept only its own commands and javascript. You can not do this with its own commands, so you use javascript. This is exactly a reason I gave you a link to a faster method of computing distance in JS. – Salvador Dali Mar 29 '14 at 22:14