Filter Documents by Distance Stored in Document with $near Filter Documents by Distance Stored in Document with $near mongoose mongoose

Filter Documents by Distance Stored in Document with $near


Presuming you have already worked out to act on the event data as you recieve it and have it in hand ( if you have not, then that is another question, but look at tailable cursors ), then you should have an object with that data for which to query the users with.

This is therefore not a case for JavaScript evaluation with $where, as it cannot access the query data returned from a $near operation anyway. What you want instead is $geoNear from the aggregation framework. This can project the "distance" found from the query, and allow a later stage to "filter" the results against the user stored value for the maximum distance they want to travel to published events:

// Represent retrieved event datavar eventData = {  eventLocation: {    latlong: [long,lat]  }};// Find users near that event within their stored distanceUser.aggregate(  [    { "$geoNear": {      "near": {        "type": "Point",        "coordinates": eventData.eventLocation.latlong      },      "distanceField": "eventDistance",      "limit": 100000,      "spherical": true    }},    { "$redact": {      "$cond": {        "if": { "$lt": [ "$eventDistance", "$maxDistance" ] },        "then": "$$KEEP",        "else": "$$PRUNE"      }    }}  ]  function(err,results) {    // Work with results in here  })

Now you do need to be careful with the returned number, as since you appear to be storing in "legacy coordinate pairs" instead of GeoJSON, then the distance returned from this operation will be in radians and not a standard distance. So presuming you are storing in "miles" or "kilometers" on the user objects then you need to calculate via the formula mentioned in the manual under "Calculate Distances Using Spherical Geometry" as mentioned in the manual.

The basics are that you need to divide by the equatorial radius of the earth, being either 3,963.2 miles or 6,378.1 kilometers to convert for a comparison to what you have stored.

The alternate is to store in GeoJSON instead, where there is a consistent measurement in meters.

Assuming "kilometers" that "if" line becomes:

"if": { "$lt": [    "$eventDistance",    { "$divide": [ "$maxDistance", 6,378.1 ] } ]},

To reliably compare your stored kilometer value to the radian result retured.

The other thing to be aware of is that $geoNear has a default "limit" of 100 results, so you need to "pump up" the "limit" argument there to the number for expected users to possibly match. You might even want to do this in "range lists" of user id's for a really large system, but you can go as big as memory allows within a single aggreation operation and possibly add allowDiskUse where needed.

If you don't tune that parameter, then only the nearest 100 results ( default ) will be returned, which may well no even suit your next operation of filtering those "near" the event to start with. Use common sense though, as you surely have a max distance to even filter out potential users, and that can be added to the query as well.

As stated, the point here is returning the distance for comparison, so the next stage is the $redact operation which can fiter the user's own "travel distance" value against the returned distance from the event. The end result gives only those users that fall within their own distance contraint from the event who will qualify for notification.

That's the logic. You project the distance from the user to the event and then compare to the user stored value for what distance they are prepared to travel. No JavaScript, and all native operators that make it quite fast.

Also as noted in the options and the general commentary, I really do suggest you use a "2dsphere" index for accurate spherical distance calculation as well as converting to GeoJSON storage for your coordinate storage in your database Objects, as they are both general standards that produce consistent results.


Try it without embedding your query in $where: {. The $where operator is for passing a javascript function to the database, which you don't seem to want to do here (and is in fact something you should generally avoid for performance and security reasons). It has nothing to do with location.

{  'location.latlong': {    $near: {      $geometry: {        type: "Point",        coordinates: [long,lat]      },      $maxDistance: this.distance    }  }}