简体   繁体   中英

Mongoid and querying for embedded locations?

I have a model along the lines of:

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) .

I want to query the City collection to return all cities that have at least 1 Store in a nearby location. 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.

Mike,

The feature you are requesting is called multi-location documents. It is not supported in the current stable release 1.8.2. This is available only from version 1.9.1.

And Querying is straightforward when use mongoid, its like this

   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. You can read more about this here .

Use $within query instead to get the correct results

Same query written using $within and $centerSphere

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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