Question

Is there a way to perform math in the find function as is possible in MySQL? I have the following sql query for performing searches based on radius in MySQL:

SELECT id,(3959 * acos(cos(radians(37)) * cos(radians(lat)) * cos( radians(lng) -     radians(-122)) + sin(radians(37)) * sin(radians(lat)))) 
AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;

And would like to be able to perform something similar in mongodb or node.js. Is this possible?

Was it helpful?

Solution

The MongoDB query language and aggregation framework only has very limited mathematical operators.

But MongoDB can use arbitrary Javascript functions to filter results with the $where - operator. This allows you to create find-queries with very complex conditions. But keep in mind that this method is quite slow (although not necessarily much slower than in SQL).

But looking at your column names, you seem to be working with geographical data. MongoDB has a very feature-rich and efficient framework for indexing and querying geospatial data. Using this might also be an option for you which would be a lot faster and much easier to use than dealing with trigonometric functions directly.

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