【问题标题】:Mongoid and querying for embedded locations?Mongoid 和查询嵌入式位置?
【发布时间】:2011-10-03 02:13:18
【问题描述】:

我有一个模型如下:

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 文档。

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    迈克,

    您请求的功能称为多位置文档。当前的稳定版本 1.8.2 不支持它。这仅在版本 1.9.1 中可用。

    而且使用mongoid时查询很简单,就是这样

       City.near("stores.location" =>  @location)
    

    在多位置文档中使用近距离查询时要小心,因为同一文档可能会被多次返回,因为 $near 查询会返回按距离排序的结果。你可以阅读更多关于这个here的信息。

    使用 $within 查询来获得正确的结果

    使用 $within 和 $centerSphere 编写的相同查询

    EARTH_RADIUS = 6371
    distance = 5
    City.where("stores.location" => {"$within" => {"$centerSphere" => [@location, (distance.fdiv EARTH_RADIUS)]}})
    

    【讨论】:

    • 非常有帮助的答案。谢谢。
    • 查询Stores 的集合并引用Cities 会更快吗?
    • @Mike A,你不必担心这个。它会是一样的。
    猜你喜欢
    • 2012-04-26
    • 2015-05-13
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多