简体   繁体   English

Mongoid 和查询嵌入式位置?

[英]Mongoid and querying for embedded locations?

I have a model along the lines of:我有一个 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

Then I tried calling something like City.stores.near(@location) .然后我试着打电话给City.stores.near(@location)

I want to query the City collection to return all cities that have at least 1 Store in a nearby location.我想查询City集合以返回在附近位置至少有 1 Store的所有城市。 How should I set up the index?我应该如何设置索引? What would be the fastest call?最快的电话是什么?

I read the Mongoid documentation with using index [[:location, Mongo::GEO2D]] but I am not sure how this applies to an embedded document, or how to only fetch the City and not all the Stop documents.我使用index [[:location, Mongo::GEO2D]]阅读了 Mongoid 文档,但我不确定这如何应用于嵌入式文档,或者如何仅获取City而不是所有Stop文档。

Mike,麦克风,

The feature you are requesting is called multi-location documents.您请求的功能称为多位置文档。 It is not supported in the current stable release 1.8.2.当前的稳定版本 1.8.2 不支持它。 This is available only from version 1.9.1.这仅在版本 1.9.1 中可用。

And Querying is straightforward when use mongoid, its like this并且使用mongoid时查询很简单,就像这样

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

And be careful when using near queries in multi-location documents, because the same document may be returned multiple times, since $near queries return ordered results by distance.在多位置文档中使用近距离查询时要小心,因为可能会多次返回同一个文档,因为 $near 查询会返回按距离排序的结果。 You can read more about this here .您可以在此处阅读有关此内容的更多信息。

Use $within query instead to get the correct results改用 $within 查询来获得正确的结果

Same query written using $within and $centerSphere使用 $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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM