Ambiguity about $geoNear in aggregate query

廉价感情. 提交于 2019-12-11 06:09:15

问题


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.


回答1:


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"] }}}
])


来源:https://stackoverflow.com/questions/54667241/ambiguity-about-geonear-in-aggregate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!