【发布时间】:2016-03-14 12:46:10
【问题描述】:
我有两个模型,Location 和 Event。
class Event
include Mongoid::Document
field :name, type: String
belongs_to :location
index({'location.coordinates' => '2d'}, {unique: true}) # I added this later on because I had an error when querying on location.coordinates
end
class Location
include Mongoid::Document
field :coordinates, type: Array
index({coordinates: '2d'}, {unique: true})
has_many :events
end
现在,如果我创建一个带有关联位置的 Event
Location.create({coordinates: [40.7127837, -74.0059413]})
Event.create({name: "foo", location: Location.first})
如何查询特定位置附近的事件? 我试过这个:
Event.where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
但它不返回任何结果,而
Location.where('coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
返回之前创建的Location 对象。
我做错了什么?
【问题讨论】:
-
我没有使用过 ruby,请参阅此处了解如何使用 mongo docs.mongodb.org/manual/reference/operator/query/nearSphere 进行 nearSphere 查询。 $near 和 $nearSphere 是不同的。 maxDistance 应该以米为单位。 1000.fdiv(111.12) 是什么意思?
-
从here,
1000.fdiv(111.12)应该将公里转换为度(所以 1000 公里以度为单位)。我编辑了我的问题,事实上,如果我直接查询Location模型,$near就可以工作,所以我认为它与 mongoid 有更多关系...... -
度数还是弧度?对不起,我不熟悉 ruby 语法,但 mongo 不支持度值,它必须是弧度。 $nearSphere 算法将距离计算为球体,而 $near 仅计算为平面。对于地理位置计算,$nearSphere 将为您提供准确的结果。
标签: ruby-on-rails ruby mongodb mongoid geo