我有代表本地商家提供的服务的 Mongoid 文档。每个都有一个或多个位置(纬度/经度点)和一个服务区域(半径)。给定客户位置(纬度/经度点),如何找到客户位置在服务区域内的所有文档?
class Service
include Mongoid::Document
# Data currently stored like this:
field :address, type: String
field :service_distance, type: Float
# Happy to geocdoe and store in another format
end
大多数示例基于搜索圆内的点(其中半径是查询的一部分并且对所有文档都相同)而不是寻找与点相交的圆(其中圆具有不同的半径)。
最佳答案
通过指定“中心”和“半径”为“圆”建模是一种有效的方法,但如果不是很明显的话,找到“圆内”的东西通常也很简单:
Service.collection.aggregate([
# Get the distance from the current location
{ "$geoNear" => {
"near" => {
"type" => "Point",
"coordinates" => [ 1, 1 ]
},
"distanceField" => "dist"
}},
# Find out if the "dist" is within the radius
{ "$project" => {
"address" => 1,
"service_distance" =>1,
"location" => 1, # the field with the co-ordinates you add
"dist" => 1,
"within" => { "$lt" => [ "$dist", "$service_distance" ] }
}},
# Then filter out anything not "within"
{ "$match" => { "within" => true } }
])
所以 $geoNear
aggregation运算符不仅会找到“靠近”指定点的文档,还会将一个字段“转换”到文档中,表示与查询中该点的“距离”。
请注意,您在此处要求的“额外字段”(“位置”)是“商店”所在圆心的“点”的实际“坐标”。这是此处所需的附加字段。
接下来要做的是将计算出的距离与文档中包含的“半径”或“service_distance”进行“比较”,看看它是否“小于”或“在”该距离内。
然后,如果结果为 true
,您将保留这些文档并在您的最终回复中展示它们。
此处的 .collection
访问器允许您使用 native MongoDB 方法,例如 .aggregate()
,它允许进行此类操作。
这就是您在服务器处理中的处理方式。
关于mongodb - 查找包含点的 Mongodb 地理空间圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30850339/