electronicbites
electronicbites

Reputation: 104

Finding distinct rows in scope with mongoid

I have two models in my rails project: persons and an embeded collection, cities. there is also a spatial index on the cities. I want to find all persons near one city.

class Person
 include Mongoid::Document
 include Mongoid::Timestamps
 embeds_many :cities
 scope :nearby, ->(location, distance) { where('cities.location' => 
                    {'$near' => location , '$maxDistance' => distance})}


class City
  include Mongoid::Document
  include Mongoid::Timestamps
  embedded_in :person
  field :city
  field :location, type: Array  #0: latitude, 1: longitude

location_in_new_york = [40.71892, -74.00131]

My query would be

Person.nearby(location_in_new_york, 1)

But doing so a person with two cities which are very close to each other get found twice. How can I avoid this behavior? I dont want to reduce this in ruby, because I would like to keep my scope.

Upvotes: 0

Views: 2172

Answers (1)

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

While not as clean as just being able to call .distinct on a criteria, this workaround gives the expected results:

Person.find(Person.nearby(location_in_new_york, 1).distinct(:_id))

This doesn't work (as written) as a scope, however, so you'd have to make it a class method. Personally, I would look into adding a patch to mongoid to add a .unique method that does what you want (since MongoDB is responsible for returning field values instead of documents when you use its distinct operator: http://www.mongodb.org/display/DOCS/Aggregation )

Upvotes: 1

Related Questions