关于聚合查询中$ geoNear的歧义
我正在建立一个基于位置的项目,我正在使用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"] }}}
])