聚合查询中有关 $geoNear 的歧义

Ambiguity about $geoNear in aggregate query

我正在建立一个使用 GeoJSON 的基于位置的项目。我用过 $geoNear 并且对它非常熟悉。现在我遇到了需要从文档列表中检查它们是否落在 maxDistance 中的情况。 这里的挑战是 maxDistance 不是预定义的。它因文档而异,并存储在文档中。

这类似于要在地图中显示的每家商店,由用户设置,以便在用户位于商店的告知距离范围内时收到通知。并且用户定义距离。 例如:用户添加一个位置并为其描述一个距离。现在,如果用户到达该位置的定义距离,用例将在地图上通知用户。

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'
   }
 }

最糟糕的方法是我用距离加载所有文档,然后循环检查它们是否落在特定距离内,但我想遵循一种好的和专业的方法。有什么线索吗?

这是位置的架构:

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

我只是将用户的当前坐标传递给查询。

您可以使用 $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"] }}}
])