Mongoid和查询嵌入式位置?

Mik*_*e A 3 ruby ruby-on-rails mongodb mongoid

我有一个模型:

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
Run Code Online (Sandbox Code Playgroud)

然后我试着打电话City.stores.near(@location).

我想查询City集合以返回Store在附近位置至少有1个的所有城市.我该如何设置索引?什么是最快的电话?

我使用Mongoid文档阅读,index [[:location, Mongo::GEO2D]]但我不确定这是如何应用于嵌入式文档,或者如何只获取City而不是所有Stop文档.

Ram*_*Vel 7

麦克风,

您请求的功能称为多位置文档.目前的稳定版本1.8.2不支持它.这仅适用于1.9.1版.

使用mongoid时查询很简单,就像这样

   City.near("stores.location" =>  @location)
Run Code Online (Sandbox Code Playgroud)

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

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

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

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