[英]Mongoid and querying for embedded locations?
我有一个 model 沿线:
class City
include Mongoid::Document
field :name
embeds_many :stores
index [["stores.location", Mongoid::GEO2D]]
end
class Store
include Mongoid::Document
field :name
field :location, :type => Array
embedded_in :cities, :inverse_of => :stores
end
然后我试着打电话给City.stores.near(@location)
。
我想查询City
集合以返回在附近位置至少有 1 Store
的所有城市。 我应该如何设置索引? 最快的电话是什么?
我使用index [[:location, Mongo::GEO2D]]
阅读了 Mongoid 文档,但我不确定这如何应用于嵌入式文档,或者如何仅获取City
而不是所有Stop
文档。
麦克风,
您请求的功能称为多位置文档。 当前的稳定版本 1.8.2 不支持它。 这仅在版本 1.9.1 中可用。
并且使用mongoid时查询很简单,就像这样
City.near("stores.location" => @location)
在多位置文档中使用近距离查询时要小心,因为可能会多次返回同一个文档,因为 $near 查询会返回按距离排序的结果。 您可以在此处阅读有关此内容的更多信息。
改用 $within 查询来获得正确的结果
使用 $within 和 $centerSphere 编写的相同查询
EARTH_RADIUS = 6371
distance = 5
City.where("stores.location" => {"$within" => {"$centerSphere" => [@location, (distance.fdiv EARTH_RADIUS)]}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.