Mike A
Mike A

Reputation: 2529

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.

Upvotes: 3

Views: 960

Answers (1)

RameshVel
RameshVel

Reputation: 65867

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)]}})

Upvotes: 7

Related Questions