使用mongoid在范围内查找不同的行

时间:2012-08-06 10:22:36

标签: ruby-on-rails mongodb mongoid

我的rails项目中有两个模型:人物和嵌入式集合,城市。城市也有空间索引。我想找到一个城市附近的所有人。

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]

我的查询将是

Person.nearby(location_in_new_york, 1)

但是,这样一个有两个彼此非常接近的城市的人会被发现两次。我该如何避免这种行为?我不想在ruby中减少这个,因为我想保留我的范围。

1 个答案:

答案 0 :(得分:1)

虽然不像在条件上调用.distinct那么干净,但这种解决方法可以提供预期结果:

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

然而,这不适用于作为范围(如所写),因此您必须使其成为类方法。就个人而言,我会考虑向mongoid添加一个补丁来添加一个.unique方法,它可以完成你想要的任务(因为当你使用它的不同运算符时,MongoDB负责返回字段值而不是文档:http://www.mongodb.org/display/DOCS/Aggregation