当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – Mongoid和查询嵌入式位置?

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有一个模型: class City include Mongoid::Document field :name embeds_many :stores index [["stores.location", Mongoid::GEO2D]]endclass Store include Mongoid::Document field :name field :location, :type = Array embedded_in :cities, :
我有一个模型:

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个商店的所有城市.我该如何设置索引?什么是最快的电话?

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

麦克风,

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

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

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

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

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

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

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