Mongoid,无法通过地理空间计算找到模型
Mongoid, Can not find models by geospatial calculation
我的模型 A
具有以下字段:
field :location, type: Array
index( { location: '2d' }, { min: -180, max: 180 })
# Check if location is float
before_save :fix_location, if: :location_changed?
def fix_location
self.location = self.location.map(&:to_f)
end
然后我有 运行 索引 rake 任务。
现在我有了坐标 [-4.430577206803733, 100.27785445050375]
的模型
我想通过它的坐标查询这个模型,我使用与我的模型相同的坐标:
loc = [-4.430577206803733, 100.27785445050375]
distance = 50 #km
models = A.where(location: {"$near" => loc, "$maxDistance" => distance.fdiv(111.12)})
当我 运行 这段代码时,它 return 什么都不做。我更改了靠近我的坐标的 loc
的值,但它仍然没有给出任何结果。
我错过了什么?
====更新====
我已将我的代码更改为:
models = A.where(location: {"$near" => {lng: 100.27785445050375, lat: -4.430577206803733}, "$maxDistance" => distance.fdiv(111.12)})
仍然给我一个空数组
您正在以纬度、经度格式存储位置坐标。 MongoDB 首先需要经度。
我找到了解决办法。我只是忘了 运行 索引 rake 任务。
我的模型 A
具有以下字段:
field :location, type: Array
index( { location: '2d' }, { min: -180, max: 180 })
# Check if location is float
before_save :fix_location, if: :location_changed?
def fix_location
self.location = self.location.map(&:to_f)
end
然后我有 运行 索引 rake 任务。
现在我有了坐标 [-4.430577206803733, 100.27785445050375]
我想通过它的坐标查询这个模型,我使用与我的模型相同的坐标:
loc = [-4.430577206803733, 100.27785445050375]
distance = 50 #km
models = A.where(location: {"$near" => loc, "$maxDistance" => distance.fdiv(111.12)})
当我 运行 这段代码时,它 return 什么都不做。我更改了靠近我的坐标的 loc
的值,但它仍然没有给出任何结果。
我错过了什么?
====更新====
我已将我的代码更改为:
models = A.where(location: {"$near" => {lng: 100.27785445050375, lat: -4.430577206803733}, "$maxDistance" => distance.fdiv(111.12)})
仍然给我一个空数组
您正在以纬度、经度格式存储位置坐标。 MongoDB 首先需要经度。
我找到了解决办法。我只是忘了 运行 索引 rake 任务。