Search code examples
node.jsmongodbmongooseaggregation-frameworkgeojson

Ambiguity about $geoNear in aggregate query


I'm setting up a location based project where I'm working with GeoJSON. I've used $geoNear and I'm pretty familiar with it. Now I've reached a situation where I need to check from a list of documents that whether they fall in the maxDistance or not. And the challenge here is maxDistance is not predefined. It varies from document to document and being stored in the document.

This is something like every store to be shown up in the map that is setup by the user to be informed when the user is in range of the told distance of store. And user defines the distance. For example: User adds a location and describe a distance for it. Now the usecase will be notify user on map if he reaches in the defined distance for that location.

Location.aggregate([
{
    $geoNear: {
    spherical: true,
    near: { type: 'Point', coordinates: [ user.location.coordinates[0], user.location.coordinates[1] ] },
    maxDistance: {Needs to be taken from each Location document and each document should be filtered against own distance},
    distanceField: 'dist.calculated'
   }
 }

The worst approach is I load all the documents with distance and then loop through to check if they fall in their specific distance but I want to follow a good and professional approach. Any clues?

Here is location's schema:

Location = new Schema({
  location: {
        type: {
          type: String,
          enum: ['Point'], 
        },
        coordinates: {
          type: [Number]
        }
    },
  distance: {
    type: Number
  }
})

And I'm simply passing user's current coordinates to the query.


Solution

  • You can use $expr

    Location.aggregate([
      { "$geoNear": {
        "spherical": true,
        "near": { "type": "Point", "coordinates": [ user.location.coordinates[0], user.location.coordinates[1] ] },
        "distanceField": "dist.calculated"
      }},
      { "$match": { "$expr": { "$lte": ["$distanceField", "$distance"] }}}
    ])